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
题目链接:https://leetcode-cn.com/problems/majority-element/
思路
这道题之前看到过,已经见识过了最厉害的方法是用投票法:
记录第一个值为res,计数为1,之后遇到和res相等的值时计数增加;不等时,若当计数大于0则计数减少,当计数为0则res更新为当前值,计数重置为1。最后如果计数大于0,则当前的值就是所求。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int num = 1, res = nums[0];
for(int i=1; i<nums.size(); ++i){
if(nums[i]==res) {
++num;
} else{
if(num==0) {
res = nums[i];
num = 1;
}else{
--num;
}
}
}
return res;
}
};
185




被折叠的 条评论
为什么被折叠?



