Description
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.
My solution
朴素的思想就是对每个值计数, 但这样实际上不止找到了majority, 其他的都找到了, 复杂度较高(因为做了无用功). 思考未果, 参考discuss
Discuss
其中一种较好的方案是采用摩尔投票法, 相同的思路, 还可以解决找出cnt > n/3 等概率的问题. 直接看代码
下面代码是记录index, 看起来不是很直观, 参见下方自己重写代码.
int majorityElement(vector<int> &num) {
int majorityIndex = 0;
for (int count = 1, i = 1; i < num.size(); i++) {
num[majorityIndex] == num[i] ? count++ : count--;
if (count == 0) {
majorityIndex = i;
count = 1;
}
}
return num[majorityIndex];
}
class Solution {
public:
int majorityElement(vector<int>& nums) {
// 参照discuss,采用摩尔投票法
// 注意摩尔法还可以解决n/3...等概率问题
int res = nums[0];
int cnt=0;
for(int i=0;i<nums.size();i++){
if(cnt==0){
res = nums[i];
cnt++;
}else{
if(nums[i]!=res) cnt--;
else cnt++;
}
}
return res;
}
};
总之, 摩尔投票法的基本思路就是找出两个不同的vote, 剔除掉, 最后剩下的一定是多数票.