-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path229. Majority Element II
45 lines (40 loc) · 1.02 KB
/
229. Majority Element II
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
class Solution {
public:
vector<int> majorityElement(vector<int>& v) {
int n=v.size();
vector<int> ans;
for(int i=0;i<n;i++){
if (ans.size() == 0 || ans[0] != v[i]) {
int cnt = 0;
for (int j = 0; j < n; j++) {
if (v[j] == v[i]) {
cnt++;
}
}
if (cnt > (n / 3))
ans.push_back(v[i]);
}
if (ans.size() == 2) break;
}
return ans;
}
};
USING MAP:
---------------------------------------------------------------------------
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int n = nums.size();
map<int, int> mpp;
vector<int> result;
for (int i = 0; i < n; i++) {
mpp[nums[i]]++;
}
for (auto it : mpp) {
if (it.second > (n / 3)) {
result.push_back(it.first);
}
}
return result;
}
};