Could anyone explain why this code did not work?


  • 0
    N
    class Solution {
    public:
        int findPairs(vector<int>& nums, int k) {
            if(nums.empty()) return 0;
            unordered_map<int, int> numMap;
            for(auto num : nums) {
                numMap[num]++;
            }
            int res = 0;
            if(!k) {
                for(unordered_map<int, int>::iterator it = numMap.begin(); it != numMap.end(); ++it) {
                    if(it->second >=2) res++;
                }
            } else {
                for(unordered_map<int, int>::iterator it = numMap.begin(); it != numMap.end(); ++it) {
                    int a = it->first;
                    if(numMap[a+k] > 0 && a+k > a) res++;
                    if(numMap[a-k] > 0 && a-k > a) res++;
                }
            }
            return res;
        }
    };
    

    The error occurs in iterating the numMap. It only iterates an element in numMap instead of iterating all of them. I do not know why this happens. This code works fine in my laptop. I guess compiler issue?


Log in to reply
 

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