532-K-diff Pairs in an Array

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.

这道题不难,主要自己想多了。而且要注意细节

public class Solution {
    public int findPairs(int[] nums, int k) {
        if(k < 0) return 0;
        Map map = new HashMap<>();
        int count = 0;
        for(int n : nums){
            map.put(n,map.getOrDefault(n,0) + 1);
        }
        for(int key : map.keySet()){
            int b = key + k;
            if(!map.containsKey(b)) continue;
            int n = map.get(b);
            int needN = (k == 0 ? 2 : 1);
            if(n >=needN){
                count++;
                map.put(key,1);
            }
        }
        return count;
    }
}

你可能感兴趣的:(532-K-diff Pairs in an Array)