K-diff Pairs in an Array
给一个数组和一个k, 找出数组中有多少个pair, 满足pair的两个数的差是k的. 这个题有些corn care是k是负的..所以要先判断k的值, 然后用一个map做counter,记录数字出现的次数, 然后利用map的key的唯一性, 遍历所有key in keySet. 记录有多少pair. 还需要注意k==0的时候, 同一个数出现两次以上, 也可以作为一个pair.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { public int findPairs(int[] nums, int k) { if(nums == null || nums.length == 0 || k < 0) return 0; int res = 0; Map<Integer, Integer> map = new HashMap<>(); for(int n : nums) { map.put(n, map.getOrDefault(n, 0) + 1); } for(int n : map.keySet()) { if(k == 0 && map.get(n) >= 2) // k == 0, [1,1] is a pair res ++; if(k != 0 && map.containsKey(n+k)) // k != 0, find another pair res ++; } return res; } } |