题目描述:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9 的数组{ 1, 2, 3, 2, 2, 2, 5, 4, 2}。由于数字2在数组中出现了5 次,超过数组长度的一半,因此输出2 。
题目分析:
方法一:基于Partition函数的O(n)算法。数组中有一个数字出现的次数超过数组长度的一半,那么排序后,要求的数肯定是中位数。所以可以利用快排的Partition函数来寻找下标是n/2的数。
方法二:根据数组特点找出O(n)的算法。数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现的次数的和还要多。因此我们可以考虑在遍历数组的时候保存两个值:一个是数组中的一个数字,一个是次数。当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1;如果下一个数字和我们之前保存的数字不同,则次数减1。如果次数为0,我们需要保存下一个数字,并把次数设为1.由于我们要找的数字出现的次数比其他所有数字出现的次数之后还要多,那么要找的数字肯定是最后一次把次数设为1时对应的数字。
public static int MoreThanHalfNum(int[] numbers) {
if (numbers == null || numbers.length < 1) {
throw new RuntimeException("wrong !!");
}
int result = numbers[0];
int count = 1;
for (int i = 1; i < numbers.length; i++) {
if (count == 0) {
result = numbers[i];
count = 1;
} else if (result == numbers[i]) {
count++;
} else {
count--;
}
}
count = 0;
for (int j = 0; j < numbers.length; j++) {
if (result == numbers[j]) {
count++;
}
}
if(count>numbers.length/2){
return result;
}else{
throw new RuntimeException("wrong !!");
}
}