Problem
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
题意
给出一个规模为n的数组,求出众数。
Note:此处对于众数的定义是出现次数大于n/2的元素
解法
利用投票算法(Majority Vote Algorithm):维护一个候选众数result和计数器count,遍历数组:
1. 如果count=0,那么就把当前元素设为候选众数,并将count置为1
2. 否则如果当前元素=候选众数,则count+1
3. 否则count-1
Note:
这个算法的原理是,众数的出现次数大于其他所有元素出现次数之和(题目中的条件是出现次数大于n/2)
Code
class Solution {
public:
int majorityElement(vector<int>& nums) {
int result = 0, count = 0;
int size = nums.size();
for (int i = 0; i < size; i++){
//如果count=0,则将当前值设为候选众数,同时count=1
if (count == 0){
result = nums[i];
count ++;
}
//否则如果当前值==候选众数,count++
else if (nums[i] == result){
count ++;
}
//否则count-1
else
count --;
}
//遍历后留下的结果即为众数
return result;
}
};