K-diff Pairs in an Array

2017/12/2 posted in  leetcode

class Solution {
public:
    int findPairs(vector<int>& nums, int k) {
        if (k<0) {
            return 0;
        }
        unordered_set<int> result;  //用集合避免重复
        unordered_map<int, int> hash;   //hash表来映射所需数值
        for (int i = 0; i<nums.size(); i++) {
            if (hash.count(nums[i]+k)) {
                result.insert(nums[i]+k);
            }
            if (hash.count(nums[i]-k)) {
                result.insert(nums[i]);
            }
            hash[nums[i]] += 1;
        }
        return result.size();
    }
};