Fork me on GitHub

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

题目描述

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

解决方案

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
27
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
unordered_map<int,int> map;
unordered_set<int> set;
for (auto num : numbers) set.insert(num);
for (auto num:numbers)
{
if (map.count(num))
{
map[num]++;
}
else
{
map[num] = 1;
}
}
for (auto num : numbers)
{
if (map[num]>(numbers.size() / 2))
{
return num;
}
}
return 0;
}
};

本文标题:数组中出现次数超过一半的数字

文章作者:LiuXiaoKun

发布时间:2019年02月20日 - 23:02

最后更新:2019年02月20日 - 23:02

原始链接:https://LiuZiQiao.github.io/2019/02/20/数组中出现次数超过一半的数字/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%