剑指offer (28)

题目 : 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0

思路 : 数组排序后,如果符合条件的数存在,则一定是数组中间那个数。(比如)
1,2,2,2,3 或 2,2,2,3,4 或2,3,4,4,4 等等

public class Solution {
	public static void main(String[] args) {
		int array[] = {1,2,4,5,3,2,3,2,2,2,2};
		System.out.println(moreThanHalfNum(array));
	}

	public static int moreThanHalfNum(int []array) {
		Arrays.sort(array);
		int count = 0;//计数,记着最多存在的数出现的次数
		for (int i = 0; i < array.length; i++) {
			if (array[i] == array[array.length/2]) {
				count++;
			}
		}
		if (count > array.length/2) {
			return array[array.length/2];
		}
		else {
			return 0 ;
		}
	}
}
发布了50 篇原创文章 · 获赞 0 · 访问量 399

猜你喜欢

转载自blog.csdn.net/weixin_46108108/article/details/104202123