Majority Element

本文详细介绍了在解决数组中多数元素问题时,包括但不限于暴力搜索、哈希表、排序、随机化、分治等五种解法的实现细节及优缺点对比。每种方法都附有相应的代码实现,旨在帮助读者理解并选择最适合特定场景的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题有多重解法,在solution里有很清楚的解释,如下:

Runtime: O(n2) — Brute force solution: Check each element if it is the majority element.
Runtime: O(n), Space: O(n) — Hash table: Maintain a hash table of the counts of each element, then find the most common one.
Runtime: O(n log n) — Sorting: As we know more than half of the array are elements of the same value, we can sort the array and all majority elements will be grouped into one contiguous chunk. Therefore, the middle (n/2th) element must also be the majority element.
Average runtime: O(n), Worst case runtime: Infinity — Randomization: Randomly pick an element and check if it is the majority element. If it is not, do the random pick again until you find the majority element. As the probability to pick the majority element is greater than 1/2, the expected number of attempts is < 2.
Runtime: O(n log n) — Divide and conquer: Divide the array into two halves, then find the majority element A in the first half and the majority element B in the second half. The global majority element must either be A or B. If A == B, then it automatically becomes the global majority element. If not, then both A and B are the candidates for the majority element, and it is suffice to check the count of occurrences for at most two candidates. The runtime complexity, T(n) = T(n/2) + 2n = O(n log n).
Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
If the counter is 0, we set the current candidate to x and the counter to 1.
If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O(n).
Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority number’s ith bit must be the one bit that has the greater count.

现将部分解法的代码给出:

最简单的,hash table法:

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

divide and conquer法:

class Solution {
public:
    int divideAndConquer(int start,int end,const vector<int>& num)
    {
        if((start+1)==end)
        {
            return num[start];
        }
        int mid=start+(end-start)/2;
        int candidateA=divideAndConquer(start,mid,num);
        int candidateB=divideAndConquer(mid,end,num);
        if(candidateA==candidateB)
        {
            return candidateA;
        }
        else
        {
            int cntA=0;
            int cntB=0;
            for(int i=start;i<end;++i)
            {
                if(num[i]==candidateA)
                {
                    cntA++;
                }
                else if(num[i]==candidateB)
                {
                    cntB++;
                }
                else
                {
                    //
                }
            }
            if(cntA>cntB)
            {
                return candidateA;
            }
            else
            {
                return candidateB;
            }
        }
    }
    int majorityElement(vector<int> &num) {
        return divideAndConquer(0,num.size(),num);
    }
};

Moore voting algorithm

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值