题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
一般解法 —— 以空间换时间
基本思想
通过HashMap存储每一个数组值出现的次数,直到找到超过一半的数字。
具体解法如下:
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer, Integer> counter = new HashMap<>();
for (int value : array) {
int times = 1;
if (counter.containsKey(value)) {
times = counter.get(value) + 1;
}
counter.put(value, times);
if (times > array.length / 2) {
return value;
}
}
return 0;
}
高级解法——根据数组特点
基本思想
对于出现次数超过一半的数,那么它的出现总次数比其他的所有都多,所有可以用他的次数去抵消其他数字出现的次数,最后还剩下的那个数就是出现次数超过一般的数。
基本步骤为:
- 在遍历数组的时候保存两个值,一个是当前检测到的出现次数最多的数,一个是次数;
- 如果下一个数字和我们保存的数相同,则次数加一,否则减一抵消。
由于可能没有出现次数超过一半的数,但遍历结果最后一个数没有抵消而留下了,我们需要最后再验证一次结果的正确性。
public int MoreThanHalfNum_Solution(int [] array) {
if (array == null || array.length == 0) {
return 0;
}
int result = array[0];
int times = 1;
for (int i = 1; i < array.length; i++) {
if (times == 0) {
result = array[i];
times = 1;
} else if (array[i] == result) {
times++;
} else {
times--;
}
}
// check the result
int check = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == result) {
check++;
}
}
if (check <= array.length/2) {
result = 0;
}
return result;
}