LC 169. Majority Element

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int max_f = 0,elem = 0;
        int n = nums.size();
        if(n==1)
            return nums[0];
        sort(nums.begin(),nums.end());
        int cnt = 1;
        for(int i=0;i<n-1;i++){
            if(nums[i] == nums[i+1]){
                cnt ++;
            }
            else{
                max_f = max(max_f,cnt);
                if(max_f == cnt)
                    elem = nums[i];
                cnt = 1;
            }
        }
        if(cnt!=1){
            max_f = max(max_f,cnt);
            if(max_f == cnt)
                elem = nums[n-1];
        }
        return elem;
    }
};


Dicussion Forum