-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path169.多数元素.cpp
50 lines (45 loc) · 936 Bytes
/
169.多数元素.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
50
/*
* @lc app=leetcode.cn id=169 lang=cpp
*
* [169] 多数元素
*/
// @lc code=start
class Solution
{
public:
int majorityElement(vector<int> &nums)
{
// int n = nums.size();
// n /= 2;
// std::unordered_map<int, int> counts;
// for (const auto &i : nums)
// {
// if (++counts[i] > n)
// {
// return i;
// }
// }
// return 0; //!
int n = nums.size();
n /= 2;
int candidate = 0;
int count = 1;
for (const auto &i : nums)
{
if (i == candidate)
{
if (++count > n)
{
break;
}
}
else if (--count == 0)
{
candidate = i;
++count; // 1
}
}
return candidate;
}
};
// @lc code=end