Leetcode 169. 多数元素(摩尔投票法) C++

在这里插入图片描述
摩尔投票法(引用力扣题解评论):
核心就是对拼消耗。
玩一个诸侯争霸的游戏,假设你方人口超过总人口一半以上,并且能保证每个人口出去干仗都能一对一同归于尽。最后还有人活下来的国家就是胜利。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int num = nums[0],count = 1;
        for(int i = 1;i < nums.size();i++){
            if(nums[i] == num) count+=1;
            else{
                count-=1;
                if(count < 0){
                    num = nums[i];
                    count = 1;
                }
            }           
        }
        return num;
    }
};

哈希表做法

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int,int> fre;
        for(int i=0;i<nums.size();i++){
            fre[nums[i]] += 1;
        }
        for(auto i = fre.begin();i != fre.end();i++){
            if(i->second > nums.size()/2){
                return i->first;
            }
        }
        return 0;
    }
};
发布了25 篇原创文章 · 获赞 25 · 访问量 2185

猜你喜欢

转载自blog.csdn.net/qq_43320728/article/details/104849931