public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if (array == null || array.length == 0)
return 0;
int count = 1;
int pre = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == pre) {
count++;
} else count--;
if (count == 0) {
pre = array[i];
count = 1;
}
}
int num = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] == pre) {
num++;
}
if (num > array.length / 2)
System.out.println(pre);
}
return pre;
}
}
剑指offer 数组中重复出现的数字(超过数组长度的一半)
最新推荐文章于 2024-08-16 23:08:28 发布