One hashmap one pass O(n) concise


  • 0
    B
    class Solution {
    public:
        int findPairs(vector<int>& nums, int k) {
            if (k < 0) {
                return 0;
            }
            unordered_map<int, bool> dict;
            int count = 0;
            for (const int& num: nums) {
                if (dict.find(num-k) != dict.end() && !dict[num-k]) {
                    ++count;
                    dict[num-k] = true;
                }
                if (dict.find(num) == dict.end() || !dict[num]) {
                    dict[num] = false;
                }
                if (k && dict.find(num+k) != dict.end() && !dict[num]) {
                    ++count;
                    dict[num] = true;
                }
            }
            return count;
        }
    };
    

Log in to reply
 

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