LeetCode Solutions

532. K-diff Pairs in an Array

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  int findPairs(vector<int>& nums, int k) {
    int ans = 0;
    unordered_map<int, int> numToIndex;

    for (int i = 0; i < nums.size(); ++i)
      numToIndex[nums[i]] = i;

    for (int i = 0; i < nums.size(); ++i) {
      const int target = nums[i] + k;
      if (numToIndex.count(target) && numToIndex[target] != i) {
        ++ans;
        numToIndex.erase(target);
      }
    }

    return ans;
  }
};
			

class Solution {
  public int findPairs(int[] nums, int k) {
    int ans = 0;
    Map<Integer, Integer> numToIndex = new HashMap<>();

    for (int i = 0; i < nums.length; ++i)
      numToIndex.put(nums[i], i);

    for (int i = 0; i < nums.length; ++i) {
      final int target = nums[i] + k;
      if (numToIndex.containsKey(target) && numToIndex.get(target) != i) {
        ++ans;
        numToIndex.remove(target);
      }
    }

    return ans;
  }
}
			

class Solution:
  def findPairs(self, nums: List[int], k: int) -> int:
    ans = 0
    numToIndex = {num: i for i, num in enumerate(nums)}

    for i, num in enumerate(nums):
      target = num + k
      if target in numToIndex and numToIndex[target] != i:
        ans += 1
        del numToIndex[target]

    return ans