C++ map


  • 0
    B
    int majorityElement(vector<int>& nums) {
        map<int,int> m;
        int ret = -1;
        for(int i = 0;i<nums.size();i++)
        {
            m[nums[i]]++;
        }
        for(map<int,int>::iterator it = m.begin();it != m.end();it++)
        {
            if((*it).second*2 >= nums.size())
            {
                 ret = (*it).first;
                 break;
            }
        }
        return ret;
    }

  • 0
    L

    no need to have second loop, m[nums[i]] can be compared with nums.size()/2 in the first loop.


Log in to reply
 

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