532. K-diff Pairs in an Array

统计一个字典,然后分情况,如果k=0的时候,计算字典中value>=2出现的次数,如果不等于0,看字典中是否存在差值为k的元素。

public int findPairs(int[] nums, int k) {
    if (k < 0) return 0;
    int res = 0;
    Map<Integer, Integer> map = new HashMap<>();
    for (int i : nums) {
        map.put(i, map.getOrDefault(i, 0) + 1);
    }

    for (Map.Entry<Integer, Integer> e : map.entrySet()) {
        if (k == 0) {
            if (e.getValue() >= 2) {
                res++;
            }
        } else {
            if (map.containsKey(e.getKey() + k)) {
                res++;
            }
        }
    }
    return res;
}

results matching ""

    No results matching ""