题目
数组中有一个数字出现的次数超过数组长度的一半
,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}
。由于数字2
在数组中出现了5次
,超过数组长度的一半,因此输出2
。
思路
题目中要找的数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现的次数的和还要多。
因此我们可以考虑在遍历数组的时候保存两个值:一个是数组中的一个数字,一个是次数,当我们遍历到下一个数字的时候,如果下一个数字和当前我们保存的数字相同,则次数加1,如果和当前我们保存的数字不同,则次数减1,当次数减到 0 的时候,我们将保存的数字改为当前遍历所处的位置,并将次数更改为1。
实现
public class Solution {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 2, 2, 2, 5, 4, 2};
int num = moreThanHalfNum(arr);
System.out.println(num);
}
public static int moreThanHalfNum(int[] arrays) {
if (arrays == null || arrays.length == 0) {
return -1;
}
int result = arrays[0];
int length = arrays.length;
int count = 1;
for (int i = 1; i < length; ++i) {
if (arrays[i] == result) {
//和当前数字相同加1
count++;
} else if (count == 0) {
//重新计数
result = arrays[i];
count = 1;
} else {
//不同则减1
count--;
}
}
return result;
}
}