
题目描述
给你一个下标从 0 开始的整数数组 nums
。如果 i < j
且 j - i != nums[j] - nums[i]
,那么我们称 (i, j)
是一个 坏数对 。
请你返回 nums
中 坏数对 的总数目。
示例 1:
输入:nums = [4,1,3,3]
输出:5
解释:数对 (0, 1) 是坏数对,因为 1 - 0 != 1 - 4 。
数对 (0, 2) 是坏数对,因为 2 - 0 != 3 - 4, 2 != -1 。
数对 (0, 3) 是坏数对,因为 3 - 0 != 3 - 4, 3 != -1 。
数对 (1, 2) 是坏数对,因为 2 - 1 != 3 - 1, 1 != 2 。
数对 (2, 3) 是坏数对,因为 3 - 2 != 3 - 3, 1 != 0 。
总共有 5 个坏数对,所以我们返回 5 。
示例 2:
输入:nums = [1,2,3,4,5]
输出:0
解释:没有坏数对。
提示:
1 <= nums.length <= 105
1 <= nums[i] <= 109
解法
方法一:式子转换 + 哈希表
根据题目描述,我们可以得知,对于任意的 \(i \lt j\),如果 \(j - i \neq \textit{nums}[j] - \textit{nums}[i]\),则 \((i, j)\) 是一个坏数对。
我们可以将式子转换为 \(i - \textit{nums}[i] \neq j - \textit{nums}[j]\)。这启发我们用哈希表 \(cnt\) 来统计 \(i - \textit{nums}[i]\) 的出现次数。
遍历数组,对于当前元素 \(\textit{nums}[i]\),我们将 \(i - cnt[i - \textit{nums}[i]]\) 加到答案中,然后将 \(i - \textit{nums}[i]\) 的出现次数加 \(1\)。
最后,我们返回答案即可。
时间复杂度 \(O(n)\),空间复杂度 \(O(n)\)。其中 \(n\) 为数组 \(\textit{nums}\) 的长度。
| class Solution:
def countBadPairs(self, nums: List[int]) -> int:
cnt = Counter()
ans = 0
for i, x in enumerate(nums):
ans += i - cnt[i - x]
cnt[i - x] += 1
return ans
|
| class Solution {
public long countBadPairs(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
long ans = 0;
for (int i = 0; i < nums.length; ++i) {
int x = i - nums[i];
ans += i - cnt.merge(x, 1, Integer::sum) + 1;
}
return ans;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12 | class Solution {
public:
long long countBadPairs(vector<int>& nums) {
unordered_map<int, int> cnt;
long long ans = 0;
for (int i = 0; i < nums.size(); ++i) {
int x = i - nums[i];
ans += i - cnt[x]++;
}
return ans;
}
};
|
| func countBadPairs(nums []int) (ans int64) {
cnt := map[int]int{}
for i, x := range nums {
x = i - x
ans += int64(i - cnt[x])
cnt[x]++
}
return
}
|
| function countBadPairs(nums: number[]): number {
const cnt = new Map<number, number>();
let ans = 0;
for (let i = 0; i < nums.length; ++i) {
const x = i - nums[i];
ans += i - (cnt.get(x) ?? 0);
cnt.set(x, (cnt.get(x) ?? 0) + 1);
}
return ans;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | use std::collections::HashMap;
impl Solution {
pub fn count_bad_pairs(nums: Vec<i32>) -> i64 {
let mut cnt: HashMap<i32, i64> = HashMap::new();
let mut ans: i64 = 0;
for (i, &num) in nums.iter().enumerate() {
let x = i as i32 - num;
let count = *cnt.get(&x).unwrap_or(&0);
ans += i as i64 - count;
*cnt.entry(x).or_insert(0) += 1;
}
ans
}
}
|