题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
练习地址
lc
L - 0169】- e - 多数元素
实现
**//方法2:时间复杂度O(n),特点:比其他所有次数都多
// 遍历数组时保存两个值,数组中的一个数字;次数
// 要找的数字为最后 一次吧次数设置成为1对应的数字**
public class C39_arry_HalfNum {
public static int halfNum(int[] array) {
if (array == null || array.length <= 0) {
return 0;
}
// 初始化,计数器为1
int res = array[0];
int times = 1; //计数器
for (int i = 1; i < array.length; i++) {
if (times == 0) {//情况1:次数为0,保存下一个数字,times置1(全部已消除,重新初始化)
res = array[i];
times = 1;
} else if (array[i] == res) {//情况2:与保存数字相同(res不重新赋值,累加相同的数的次数,消除相异的)
times++;
} else { //情况3:与保存数字不同
times--;
}
}
if (!CheckMoreThanHalf(array, res)) {
res = 0;
}
return res;
}
//检查得到的数字是否过半
static boolean CheckMoreThanHalf(int[] array, int num) {
int times = 0;
for (int a : array) {
if (a == num) {
times++;
}
}
return times * 2 > array.length;
}
}
Test
public static void main(String[] args) {
int[] arr ={1,2,3,2,2,2,5,4,2};
System.out.println(halfNum(arr));
}