1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public long countBadPairs(int[] nums) { int n = nums.length;
long res = (long) n * (n - 1) / 2; Map<Integer, Integer> countMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int num = nums[i]; int key = num - i; int count = countMap.getOrDefault(key, 0); res -= count; countMap.put(key, count + 1); } return res; } }
|
References
2364. Count Number of Bad Pairs