A generic solution that can be altered to work for any k


  • 0
    G
    class Solution {
    public:
        vector<int> majorityElement(vector<int>& nums) 
        {
            unordered_map<int,int> M;
            
            for(int i = 0; i < nums.size(); ++i)
            {
                M[nums[i]]++;
                
                if(M.size() > 2)
                {
                    for(auto &P : M)
                    {
                        P.second--;
                    }
                }
                
                auto Iter = M.begin();
                
                for(; Iter != M.end();)
                {
                    if(Iter->second == 0)
                    {
                        Iter = M.erase(Iter);
                    }
                    else
                    {
                        Iter++;
                    }
                }
            }
            
            vector<int> Result;
            
            unordered_map<int,int> Temp;
            
            for(auto & N : nums)
            {
                if(M.find(N) != M.end())
                {
                    Temp[N]++;
                }
            }
            
            for(auto &P : Temp)
            {
                if(P.second > nums.size() /3)
                {
                    Result.push_back(P.first);
                }
            }
            
            return (Result);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.