题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
private static int moreThanHalfNums(int[] nums) {
if (nums == null || nums.length == 0)
throw new RuntimeException("the length of array must be large than 0");
int result = nums[0];
int times = 1;
int len = nums.length;
for (int i = 1; i < len; i++) {
if (times == 0) {
result = nums[i];
times = 1;
} else if (result == nums[i])
times++;
else
times--;
}
times = 0;
for (int num : nums) {
if (num == result)
times++;
}
if (times > len / 2)
return result;
throw new RuntimeException("invalid input!");
}