每日一题(5)Leetcode169. Majority Element

Leetcode169

我的解决方法:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int total=1;
        int i;
        for(i=1;i<nums.size();i++){
            if(nums[i]!=nums[i-1]){
                total = 1;
            }else{
                total++;
            }
            if(total>nums.size()/2){
                break;
            }
        }
        return nums[i];
    }
};

测试样例能过,但是submit时会提示run time error。
分析:vector的sort是O(nlogn),已经很大了,我又搞了个O(n)的判定,加起来可能超过了时间限制。

以下是几种方法:
1.Sorting
虽然也是排序,但是这种方法直接返回排序后的序列的中间值,这个中间值必定是最大的。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        return nums[n/2];
    }
};

2.Hashmap

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        unordered_map<int, int> m;
        
        for(int i = 0; i < n; i++){
            m[nums[i]]++;
        }
        n = n/2;
        for(auto x: m){
            if(x.second > n){
                return x.first;
            }
        }
        return 0;
    }
};

空间复杂度稍高一点,但是时间复杂度为O(n)

3.Moore Voting Algorithm

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count = 0;
        int candidate = 0;
        
        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            
            if (num == candidate) {
                count++;
            } else {
                count--;
            }
        }
        
        return candidate;
    }
};

这个算法的思想比较巧妙:如果一个数能占到一半以上,那么它最后出现的次数能够保持正数,即使减去其他的元素出现的次数。

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值