leetcode169. 多数元素的四种解法

leetcode169. 多数元素
题目描述
给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。
1.哈希

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count = nums.size()/2; //获取数组大小的一半
        unordered_map<int, int> hashTable; //<元素,元素出现的次数>
        for(int i = 0; i < nums.size(); i++){
            hashTable[nums[i]]++;
            if(hashTable[nums[i]] > count){
                return nums[i];
            }
        }
        return 0;
    }
};

hash代码简化版

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map <int,int> mp;
        for(int n:nums)   
            if(++ mp[n] > nums.size()/2)   return n;         
        return -1;
    }
};

2.Moore投票(最优解)
摩尔投票法,投我++,不投–,超过一半以上的人投我,那我稳赢哇

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candidate = 0, votes = 0;
        for(int n : nums)
        {
            if(votes == 0)  candidate = n;  
            if(n == candidate)  ++votes;
            if(n != candidate)  --votes;
        }
        return candidate;
    }
};

3.排序

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        return nums[nums.size() / 2];       
        //因为出现频率大于n/2,所以排序后的中间位置必然是众数
    }
};

4.位运算

class Solution {
public:
    int majorityElement(vector<int>& nums) {
    int res = 0;
    for(int i = 0 ; i < 32; ++i)
    {
        int ones = 0;
        for(int n : nums)
            ones += (n >> i) & 1;              //位运算法统计每个位置上1出现的次数,每次出现则ones+1
        res += (ones > nums.size()/2) << i;    //如果1出现次数大于1/2数组的长度,1即为这个位置的目标数字
    }
    return res;
    }
};
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值