Majority Element II
Problem
Given an integer array of size n
, find all elements that appear more than ⌊ n/3 ⌋
times.
Solution Approach
Click - to see solution code
- C++
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
unordered_map<int, int> mp;
int n = nums.size();
for (int i = 0; i < n; i++) mp[nums[i]]++;
vector<int> ans;
for (auto i : mp) {
if (i.second > n / 3) ans.push_back(i.first);
}
return ans;
}
};