Leetcode 169. Majority Element

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Majority Element

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size() / 2;
unordered_map<int, int> m;
for(int num : nums) {
m[num]++;
if(m[num] > n) {
return num;
}
}
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 0;
int candidate = 0;
for(int num : nums) {
if(count == 0) {
candidate = num;
}
count += (candidate==num?1:-1);
}
return candidate;
}
};

Reference

  1. https://leetcode.com/problems/majority-element/description/
如果有收获,可以请我喝杯咖啡!