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

本文最后更新于:2022年4月9日 中午

image-20211008103821039

Solution

  • 投票法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int candidate = 0, votes = 0;
for (int num : numbers) {
if (votes == 0) candidate = num;
if (num == candidate) {
votes++;
} else {
votes--;
}
}

// 确认剩余的候选人是否超过一半
votes = count(numbers.begin(), numbers.end(), candidate);
return votes > numbers.size()/2 ? candidate : 0;
}
};
  • 借助map保存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
if (numbers.size() == 0) return 0;
int flag = numbers.size()/2 + 1;
int res = 0;
unordered_map<int, int> umap;
for (int num : numbers) {
umap[num]++;
}
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
if (iter->second >= flag) {
res = iter->first;
break;
}
}
return res;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!