forked from gh877916059/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path048. 主元素 III.cpp
49 lines (49 loc) · 833 Bytes
/
048. 主元素 III.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution
{
public:
int majorityNumber(vector<int> nums, int k)
{
unordered_map<int, int> counters;
for (auto i : nums)
{
if (counters.find(i) != counters.end())
++counters[i];
else
{
if (counters.size() < k - 1)
++counters[i];
else
{
for (unordered_map<int, int>::iterator it = counters.begin(); it != counters.end();)
{
--it->second;
if (it->second == 0)
it = counters.erase(it);
else
++it;
}
}
}
}
for (auto i : counters)
{
i.second = 0;
}
for (auto i : nums)
{
if (counters.find(i) != counters.end())
++counters[i];
}
int max_counter = 0;
int max_key = 0;
for (auto i : counters)
{
if (i.second>max_counter)
{
max_counter = i.second;
max_key = i.first;
}
}
return max_key;
}
};