LeetCode 题解工作台
统计坏数对的数目
给你一个下标从 0 开始的整数数组 nums 。如果 i 且 j - i != nums[j] - nums[i] ,那么我们称 (i, j) 是一个 坏 数对 。 请你返回 nums 中 坏数对 的总数目。 示例 1: 输入: nums = [4,1,3,3] 输出: 5 解释: 数对 (0, 1…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
根据题目描述,我们可以得知,对于任意的 $i \lt j$,如果 $j - i \neq \textit{nums}[j] - \textit{nums}[i]$,则 $(i, j)$ 是一个坏数对。 我们可以将式子转换为 $i - \textit{nums}[i] \neq j - \textit{nums}[j]$。这启发我们用哈希表 来统计 $i - \textit{nums}[i]$ 的…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 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 <= 1051 <= 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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidate's ability to recognize the connection between index and value differences.
- question_mark
Efficiency in counting bad pairs by leveraging hash tables.
- question_mark
Understanding of transforming a complex problem into a counting problem.
常见陷阱
外企场景- error
Not recognizing the need for a hash table to track index-value differences.
- error
Misunderstanding the problem by attempting to check each pair directly with nested loops, leading to O(n^2) complexity.
- error
Overlooking the importance of transforming the problem to count non-bad pairs.
进阶变体
外企场景- arrow_right_alt
Handling larger arrays efficiently (up to length 10^5).
- arrow_right_alt
Adjusting the solution for arrays containing negative numbers or large values.
- arrow_right_alt
Finding the number of non-bad pairs instead of bad pairs.