This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> majorityElement(vector<int>& nums) { | |
int len = nums.size(); | |
unordered_map<int, int> map; | |
for(int i = 0; i < len; ++i) | |
{ | |
int num = nums[i]; | |
if(map.size() <= 1 || map.find(num) != map.end()) | |
++map[num]; | |
else | |
{ | |
auto iter = map.begin(); | |
while(iter != map.end()) | |
{ | |
if(--(iter->second) == 0) | |
map.erase(iter++); | |
else | |
++iter; | |
} | |
} | |
} | |
//check if elements in map are majoirity elements | |
vector<int> res; | |
for(auto& p : map) | |
p.second = 0; | |
for(int i = 0; i < len; ++i) | |
if(map.find(nums[i]) != map.end()) | |
++map[nums[i]]; | |
for(auto& p : map) | |
if(p.second * 3 > len) | |
res.emplace_back(p.first); | |
return res; | |
} | |
}; |
No comments:
Post a Comment