Untitled
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