class Solution {
public:
int majorityElement(vector<int>& nums) {
if (nums.empty())
return0;
unordered_map<int, int> cache;
for (auto v : nums) {
cache[v]++;
}
int maxElem = nums[0];
int maxCnt = -1;
for (auto v : cache) {
if (v.second > maxCnt) {
maxCnt = v.second;
maxElem = v.first;
}
}
return maxElem;
}
};
python
classSolution(object):defmajorityElement(self, nums):"""
:type nums: List[int]
:rtype: int
"""
cache={}
for v in nums:
if cache.get(v,'N/A') == 'N/A':
cache[v] = 1else:
cache[v] += 1
maxElem = -1
maxCnt = -1for k, v in cache.iteritems():
if v > maxCnt:
maxElem, maxCnt = k, v
return maxElem