题目描述:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数 字。如果不存在则输出0。
思路:将首次出现的数count+1,与之后的数进行比较,相等则+1,否则—1,最 后进行校验是否超过长度的一半。
//:将首次出现的数count+1,与之后的数进行比较,
// 相等则+1,否则—1,
// 最后进行校验是否超过长度的一半。
package Function;
public class moreThanHalfNum39 {
public static int moreThanHalfNum(int[] nums) {
int count = 0;
int candidate = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return checkMoreThanHalf(nums, candidate) ? candidate : 0;
}
private static boolean checkMoreThanHalf(int[] array, Integer number) { int times = 0; for (int i : array) {if (i == number) { times++; }
}
return times * 2 >= array.length;
}
}