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;