Untitled
unknown
plain_text
2 years ago
445 B
9
Indexable
class Solution {
public:
int majorityElement(vector<int>& nums) {
int cnt=0,elem=nums[0];
for(int i=0;i<nums.size();i++){
if(nums[i]==elem)cnt++;
else cnt--;
if(cnt==0){
elem=nums[i+1];//this might be our new majority element,the previous got cancelled to0
}
}
if(cnt>0) return elem;
else return -1;
}
};Editor is loading...
Leave a Comment