congr / world

2 stars 1 forks source link

LeetCode : 532. K-diff Pairs in an Array #462

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/k-diff-pairs-in-an-array/

image

congr commented 5 years ago

image

image

congr commented 5 years ago

O(N)

class Solution {
    public int findPairs(int[] nums, int k) {
        if (k < 0) return 0; // !!! edge case

        int cnt = 0;
        Map<Integer, Integer> map = new HashMap(); // value, count
        for (int n : nums) map.merge(n, 1, Integer::sum);

        for (int key : map.keySet()) {
            if (k == 0) {
                if (map.get(key) >= 2) cnt++; // [1,1,1,1] -> (1,1)
            } else if (map.containsKey(key + k)) cnt++;
        }

        return cnt;
    }
}