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.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
思路:
1.使用map<int,int> mp,标记次数,然后找到次数最多的那个。T:O(N) , S:O(N).
参考代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int,int> mp;
int Max=nums[0];
for(int i=0;i<nums.size();i++){
mp[nums[i]]++;
if(nums[i]!=Max&&mp[nums[i]]>mp[Max])
Max=nums[i];
}
return Max;
}
};
优化:Boyer-Moore Majority Vote Algorithm(
摩尔投票法)。设置一个计数器cnt用来标记主元素major,然后遍历数组,每次当前元素和major不同时cnt--,相同cnt++,若cnt==0,则更换major,并使cnt=1.
参考代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int major=nums[0],cnt=0;
for(int i=0;i<nums.size();i++){
if(cnt==0){
cnt=1;
major=nums[i];
}else if(major==nums[i]) {
cnt++;
}else cnt--;
}
return major;
}
};