Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
433 B
1
Indexable
class Solution {
public:
    int majorityElement(vector<int>& arr) {
        sort(arr.begin(),arr.end());
        int n=arr.size();
        int cnt=0;
        int elem=arr[0];
        for(int i=0;i<n;i++){
            if(arr[i]==elem) {
                cnt++;
            }else{
                cnt--;
            }
            if(cnt<=0){
                elem=arr[i];
            }
        }
        return (cnt>0)?elem:-1;
    }
};
Leave a Comment