178.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.
给定一个整数数组和一个整数k,您需要找到数组中唯一的k-diff对的数量。 这里k-diff对被定义为整数对(i,j),其中i和j都是数组中的数字,它们的绝对差是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.
数组中有两个2-diff对,(1,3)和(3,5)。
虽然我们在输入中有两个1,但我们应该只返回唯一对的数量。
Example 2:
Input:[1, 2, 3, 4, 5], k = 1 Output: 4 Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
数组中有四个1-diff对,(1,2),(2,3),(3,4)和(4,5)。
Example 3:
Input: [1, 3, 1, 5, 4], k = 0 Output: 1 Explanation: There is one 0-diff pair in the array, (1, 1).
说明:数组中有一个0-diff对,(1,1)。
Note:
- The pairs (i, j) and (j, i) count as the same pair.对(i,j)和(j,i)计为同一对。
- The length of the array won't exceed 10,000.阵列的长度不会超过10,000。
- All the integers in the given input belong to the range: [-1e7, 1e7].给定输入中的所有整数都属于以下范围:[ - 1e7,1e7]。
解答:
方法一:
1 class Solution { 2 public int findPairs(int[] nums, int k) { 3 Arrays.sort(nums); 4 5 int right=0; 6 int res=0; 7 8 for(int left=0;left<nums.length;left++){ 9 right=Math.max(right,left+1); 10 while(right<nums.length && nums[right]-nums[left]<k) 11 right++; 12 if(right<nums.length && nums[right]-nums[left]==k) 13 res++; 14 while(left<nums.length-1 && nums[left]==nums[left+1]) 15 left++; 16 17 } 18 return res; 19 } 20 }
方法二:
1 class Solution { 2 public int findPairs(int[] nums, int k) { 3 int res=0; 4 Map<Integer,Integer> map=new HashMap<>(); 5 6 for(int num:nums) 7 map.put(num,map.getOrDefault(num,0)+1); 8 9 for(int key:map.keySet()){ 10 if(k==0 && map.get(key)>1) 11 res++; 12 else if(k>0 && map.containsKey(key+k)) 13 res++; 14 } 15 16 return res; 17 } 18 }
详解:
思路一:
先给数组排序 ,然后利用滑动窗口的双指针。
遍历排序后的数组,找到第一个right-left>=k的数字,如果=k,res++;然后循环去掉和当前left所指数字相同的数。
思路二:
用哈希表建立当前无序数组中的数和出现次数的映射。
遍历哈希表,如果k=0,且该数字出现次数>1,res++;如果k不为0,当前数字+k也存在于哈希表中,res++