[leetcode] Majority Element

Majority Element

class Solution {
public:
    int majorityElement(vector<int> &num) {
        if(num.size()==0){
            return -1;
        }
        int alternative=num[0];
        int cnt=1;
        for(int i=1;i<num.size();i++){
            if(alternative==num[i]){
                cnt++;
            }else{
                cnt--;
                if(cnt==0){
                    alternative=num[i];
                    cnt=1;
                }
            }
        }
        //verify the result
        cnt=0;
        for(int j=0;j<num.size();j++){
            if(alternative==num[j]){
                cnt++;
            }
        }
        if(cnt>num.size()/2){
            return alternative;
        }else{
            return -1;
        }
    }
};



你可能感兴趣的:([leetcode] Majority Element)