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.这道题的意思是,输入一个整数数组和一个整数k,咱们须要找出数组中绝对值差正好为k的不重复的整数对儿数组
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
这个例子中有两个不一样的整数对, (1, 3)和(3, 5).codeExample 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
这个例子里有四个不一样的整数对(1, 2), (2, 3), (3, 4)和(4, 5).getExample 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
这个例子里有一个符合要求的整数对(1,1)hash
int res = 0; if(k < 0)return 0; if(k == 0){ HashMap<Integer,Integer> countZero = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(countZero.containsKey(nums[i])){ if(countZero.get(nums[i]) == 1){ res ++; countZero.put(nums[i], 2); } }else{ countZero.put(nums[i], 1); } } }else{ Set<Integer> count = new HashSet<Integer>(); for(int num : nums){ if(!count.add(num)){continue;} if(count.contains(num+k)){ res ++; } if(count.contains(num-k)){ res ++; } } } return res;