文章524
标签277
分类67

算法:数组中出现次数超过一半的数字


数组中出现次数超过一半的数字

数组中出现次数超过一半的数字

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。

如果不存在则输出0。


分析

使用摩尔投票法[求众数]

在遍历数组时保存两个值:一是数组中一个数字,一是次数。

遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。

遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
public int MoreThanHalfNum_Solution(int[] array) {
if (array == null || array.length == 0) throw new RuntimeException("Invalid parameter");
if (array.length == 1) return array[0];

int curNum = array[0], count = 1, len = array.length;
for (int i = 1; i < len; ++i) {
if (array[i] == curNum) {
count++;
} else {
count--;
if (count == 0) {
curNum = array[i];
count++;
}
}
}

int bound = len / 2;
int cnt = 0;
for (int n : array) {
if (n == curNum) cnt++;
}
return cnt > bound ? curNum : 0;
}
}

本文作者:Jasonkay
本文链接:https://jasonkayzk.github.io/cn/1996/07/27/%E7%AE%97%E6%B3%95-%E6%95%B0%E7%BB%84%E4%B8%AD%E5%87%BA%E7%8E%B0%E6%AC%A1%E6%95%B0%E8%B6%85%E8%BF%87%E4%B8%80%E5%8D%8A%E7%9A%84%E6%95%B0%E5%AD%97/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可