C++ code using map


  • 0
    C
    class Solution {
    public:
        int majorityElement(vector<int>& nums) 
        {
            map<int, int> cnt;
            for(int i=0; i < nums.size(); i++)
                cnt[ nums[i] ]++;
                
            int n = nums.size();
            for(map<int, int>::iterator iter = cnt.begin(); iter != cnt.end(); iter++)
                if( iter->second > n/2 )
                    return iter->first;
        }
    };

  • 0
    C

    cnt[ nums[i] ]++;
    Hi,I'm quite curious about this line,don't I need to initialize the cnt first?
    I thought there will be memory leakage...because there is no value for key nums[i].
    Am I wrong?


Log in to reply
 

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