数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
比如输入一个长度为9的数组{1,2,3,2。2,2。5,4,2}。因为数字2在数组中出现5次,超过数组长度的一半,因此输出2.
代码
公共代码
/**
* 快排
* @param array
* @param lo
* @param hi
*/
public static void sort(int[] array,int lo ,int hi){
if(lo>=hi){
return ;
}
int index=partition(array,lo,hi);
sort(array,lo,index-1);
sort(array,index+1,hi);
}
public static int partition(int []array,int start,int end){
// 固定的切分方式
int key = array[start];
while(start < end){
// 从后半部分向前扫描
while(end > start && array[end] >= key){
end--;
}
array[start] = array[end];
// 从前半部分向后扫描
while(start < end && array[start] < key){
start++;
}
array[end]=array[start];
}
array[start]=key;
return end;
}
解法一
因为是数组,并且出现次数超过数组长度一半,对数组排序,那么排序后的数组的中位数应该就是要找的数字。所以先采用快速排序使数组有序,然后验证中位数是否满足条件。
private static Integer findMoreThanHalf1(int[] array) {
if (array == null || array.length == 0) {
return null;
}
int length = array.length;
int middle = length >> 1;
// 实际开发中,谁会自己写排序啊,直接用现成的就OK了
// Arrays.sort(array)
sort(array, 0, length - 1);
int result = array[middle];
if (!isExist(array, result)) {
return null;
}
return result;
}
解法二
一个元素出现的次数超过一半,也就是说,其他元素出现次数之和也没有该元素多,即 count(target) - count(others) > 0,所以比较前后两个数,相等 + 1,不相等 - 1,当为0时更新记录的数字,遍历一遍后,如果存在这样的数字,计数器应 > 0,此时记录的数字就是要找的数字。
public static Integer findMoreThanHalf2(int[] array) {
if (array == null || array.length == 0) {
return null;
}
// 初始化结果result及用于计数的count
int result = array[0];
int count = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == result) {
// 如果相等,则计数器+1
count++;
} else {
// 如果不相等,则计数器-1
count--;
}
if (count == 0) {
// 如果此时count为0,更新result值
result = array[i];
count = 1;
}
}
// 1. 计数器等于0时,说明不存在,因为是大于数组长度的一半,所以不考虑等于一半的情况
// 2. 计数器大于0时,再次验证该数字的出现次数是否真的大于数组长度的一半
if (count == 0 && !isExist(array, result)) {
return null;
}
return result;
}