Count Number of Pairs With Absolute Difference K
给一个数组, 和一个数字k, 求数组中的pair的个数, 他们的绝对值差等于k.
这题就存一下数字, 然后因为数字大小范围是[1,200], 所以直接算一下这个范围可能的结果即可.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution { public int countKDifference(int[] nums, int k) { int res = 0; Map<Integer, Integer> count = new HashMap<>(); for(int n : nums) count.put(n, count.getOrDefault(n, 0) + 1); for(int i = 1; i <= 100 ; i++){ int a = count.getOrDefault(i, 0); int b = count.getOrDefault(i + k,0); if(a != 0 && b != 0){ res += a * b; } } return res; } } |