【LeetCode】Majority Element两种做法对比

Majority Element
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.
做法1
思路很简单,先排序,然后在中间的一定是出现最多的。为什么呢?因为它出现more than n/2次,所以它前后元素一定不会超过n/2个。排序采取了快排,好久没写还有点生疏了。但是这个做法却LTE了,尴尬。。
代码

class Solution {
public:
    int majorityElement(vector<int> &num) {
        int len = num.size();
        quickSort(num,0,len-1);
        return num[len/2];
    }
    void quickSort(vector<int> &num,int low,int high){
        if (low>=high) return;
        int i=low;int j=high;
        int pivot = num[i];
        while (i<j){
            while (i<j&&num[j]>=pivot){j--;}
            num[i]=num[j];
            while (i<j&&num[i]<=pivot){i++;}
            num[j]=num[i];
        }
        num[i]=pivot;
        quickSort(num,low,i-1);
        quickSort(num,i+1,high);

    }
};

做法2
思路:既然最多元素出现了n/2次,那我就想用抵消的思想,用它和与它不相等的元素一一相消,剩下的一定就是最多的那个元素。根据这个想法,有了如下代码。

class Solution {
public:
    int majorityElement(vector<int> &num) {
        int result=num[0];int len = num.size();
        int count = 0;
        for (int i=0;i<len;i++){
            if (count==0||result==num[i]) {
                result = num[i];count++;}   //count清零时,取当前数作为result
            else count--;
        }
        return result;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值