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.

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

思路:解法时间复杂度O(n),空间复杂度O(1)。思路有点诡异。可以用反证法证明正确性。

如果这种方法是错误的,则必然存在一个k,能通过该算法,且不是MajorityElement(记为m),记数组长度为n。考虑最好的情况,k从数组开始处一直连续多个,中间没有遇到其他数字(这种情况对k最有利,因为完成了“原始积累”,不会被意外淘汰。)当k完成“原始积累”后,其count值不超过n/2,而以后的路上还有至少 n/2+1 个m,count--至少执行 n/2+1 次,count为负数,则k被淘汰。这与k能通过该算法且k不是m相矛盾;而在k不是最好的情况下,就更会被淘汰了。
正向理解的话,可以认为数字之间互相消除,玩对抗游戏:
(1).m与其他数字一对一相消:显然,这能保证m获胜;
(2).其他数字与不同数字相消:这种损失使得其他数字对抗m的能力更弱了。
(3).m与m叠加,其他数字与相同数字叠加:这两种叠加的情况最后都等价于(1)和(2),只是延迟了这一过程;
附:1、直观的统计法,时间复杂度O(n^2),空间复杂度O(n)。

class Solution {
public:
    int majorityElement(vector<int> &num) {
        int numSize = num.size();
        int values[numSize], counts[numSize];
        int i,j,n = 0;
        bool exist = false;
        for(i = 0; i < numSize; i++) {
            exist = false;
            for(j = 0; j < n; j++) {
                if(values[j]==num[i]) {
                    exist = true;
                    counts[j]++;
                }
        }
        if(!exist) {
            values[n] = num[i];
            counts[n] = 1;
            n++;
        }
    }
    for(i = 0; i < n; i++) {
            if(counts[i] > numSize / 2) return values[i];
        }
    }
};

2、先排序的方法,时间复杂度O(nlogn),空间复杂度O(1)。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值