Question:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Solution:
使用map记录每个数字出现的次数,发现符合就返回。
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int> m;
for (int i = 0; i < nums.size(); i++) {
if (m.find(nums[i]) == m.end()) {
m[nums[i]] = 1;
} else {
m[nums[i]]++;
}
if (m[nums[i]] > nums.size()/2) {
return nums[i];
}
}
}
};
时间复杂度:O(n)
空间复杂度:O(n)