筷子与饺子
Published on 2019-11-11 04:08 in 暂未分类 with 筷子与饺子

169. 多数元素

题目

169.多数元素
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [3,2,3]
输出: 3
示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

题解

class Solution {
public:
    int majorityElement(vector<int>& nums) {
//摩尔投票法,先假设第一个数过半数并设cnt=1;遍历后面的数如果相同则cnt+1,不同则减一,当cnt为0时则更换新的数字为候选数(成立前提:有出现次数大于n/2的数存在)
        int res=0,cnt=0;
        for(int i=0;i<nums.size();i++){
            if(cnt==0) {
                res=nums[i];
                cnt++;
            }
            else{
                res==nums[i]?cnt++:cnt--;
            }
        }
        return res;
    }
};

posted @ 2020-03-08 23:38  筷子与饺子  阅读(112)  评论(0编辑  收藏  举报