question about loop over map


  • 0
    B

    The following code gives wrong answer, the issue if the line:

    if( map[it->first+k]>thresh)
    

    Seems the loop will terminate if you check a non-existed key.
    Anybody know the reason? On MSVC, it works.

        int findPairs(vector<int>& nums, int k) {
            if(k<0) return 0;
            unordered_map<int, int> map;
            int total = 0;
            for (auto x : nums)
            {
                map[x]++;
            }
            int thresh = !k;
            for (auto it = map.begin();it!=map.end();it++)
            {
                if( map[it->first+k]>thresh)  // this code causes problem
                    total++;                
            }
            return total;
        }
    

Log in to reply
 

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