comments | difficulty | edit_url | rating | source | tags | ||||
---|---|---|---|---|---|---|---|---|---|
true |
中等 |
1622 |
第 84 场双周赛 Q2 |
|
给你一个下标从 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
根据题目描述,我们可以得知,对于任意的
我们可以将式子转换为
遍历数组,对于当前元素
最后,我们返回答案即可。
时间复杂度
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;
}
}
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;
}
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
}
}