C++ O(N) Time with unordered_map
See my latest update in repo LeetCode\n\n\n// OJ: https://leetcode.com/problems/k-diff-pairs-in-an-array\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Sp
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n```\n// OJ: https://leetcode.com/problems/k-diff-pairs-in-an-array\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(N)\nclass Solution {\npublic:\n  int findPairs(vector<int>& nums, int k) {\n    if (k < 0) return 0;\n    unordered_map<int, int> m;\n    for (int n : nums) m[n]++;\n    int cnt = 0;\n    for (auto p : m) {\n      if ((!k && p.second > 1)\n        || (k && m.count(p.first + k))) ++cnt;\n    }\n    return cnt;\n  }\n};\n```\n\n---\n\nUpdate 2022/02/08:\n\nBack on 2017/06/06, the constraint of this problem was as follows (You can see the full problem description [here](https://github.com/lzl124631x/LeetCode/commit/8536736d9fb97483cd0875ccb7a7830b30420b24))\n\n>Given an array of integers and an integer **k**, ...\n>**Note:**  \n>\n>1.  The pairs (i, j) and (j, i) count as the same pair.\n>2.  The length of the array won\'t exceed 10,000.\n>3.  All the integers in the given input belong to the range: [-1e7, 1e7].\n\nIt didn\'t say that `k >= 0`. That\'s why I added the `k < 0` guard -- just like what we need to do in real world.\n\nNowadays, the constraints on LeetCode are much more detailed and explicit.\n\nIf I write the code today:\n\n```cpp\n// OJ: https://leetcode.com/problems/k-diff-pairs-in-an-array\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(N)\nclass Solution {\npublic:\n    int findPairs(vector<int>& A, int k) {\n        unordered_map<int, int> m;\n        for (int n : A) m[n]++;\n        int ans = 0;\n        for (auto &[n, cnt] : m) {\n            ans += k ? m.count(n - k) : cnt > 1;\n        }\n        return ans;\n    }\n};\n```
[]