-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMajority Element II.cpp
68 lines (57 loc) · 1.22 KB
/
Majority Element II.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
// Function to find the majority elements in the array
vector<int> findMajority(vector<int>& arr) {
int n = arr.size();
vector<int> sol;
unordered_map<int,int> mp;
for(int cnt:arr)
{
mp[cnt]++;
}
for(auto it:mp)
{
int first = it.first;
int second = it.second;
if(second>n/3)
{
sol.push_back(first);
}
}
int m = sol.size();
if (m == 2 && sol[0] > sol[1])
swap(sol[0], sol[1]);
return sol;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
string s;
getline(cin, s);
stringstream ss(s);
vector<int> nums;
int num;
while (ss >> num) {
nums.push_back(num);
}
Solution ob;
vector<int> ans = ob.findMajority(nums);
if (ans.empty()) {
cout << "[]";
} else {
for (auto &i : ans)
cout << i << " ";
}
cout << "\n";
}
return 0;
}
// } Driver Code Ends