[LeetCode] 2364. Count Number of Bad Pairs

You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].

Return the total number of bad pairs in nums.

Example 1:
Input: nums = [4,1,3,3]
Output: 5
Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
There are a total of 5 bad pairs, so we return 5.

Example 2:
Input: nums = [1,2,3,4,5]
Output: 0
Explanation: There are no bad pairs.

Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109

统计坏数对的数目。

给你一个下标从 0 开始的整数数组 nums 。如果 i < j 且 j - i != nums[j] - nums[i] ,那么我们称 (i, j) 是一个 坏数对 。

请你返回 nums 中 坏数对 的总数目。

思路

这是一道乍一看是O(n^2)复杂度但其实是 two sum 变种的题。题目要我们找的数对需要满足i < j 且 j - i != nums[j] - nums[i],那么我们是不是可以反过来看。首先对于一个长度为 n 的数组,所有不同下标的数对的和 = n * (n - 1) / 2,那么我们可以先统计所有的数对的和,然后再统计满足条件j - i == nums[j] - nums[i]的数对的和,两者相减就是我们要找的结果。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public long countBadPairs(int[] nums) {
/*
* j - i != nums[j] - nums[i]
* j - nums[j] != i - nums[i]
*/
HashMap<Integer, Long> map = new HashMap<>();
int n = nums.length;
long count = 0;
long res = 1L * n * (n - 1) / 2;
for (int i = 0; i < n; i++) {
int num = nums[i];
count += map.getOrDefault(i - num, 0L);
map.put(i - num, map.getOrDefault(i - num, 0L) + 1);
}
return res - count;
}
}

[LeetCode] 2364. Count Number of Bad Pairs
https://shurui91.github.io/posts/446304299.html
Author
Aaron Liu
Posted on
February 8, 2025
Licensed under