LeetCode Majority Element

来源:互联网 发布:培训课程网络促销方案 编辑:程序博客网 时间:2024/05/18 12:28

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
原创粉丝点击