LeetCode 题解工作台

统计坏数对的数目

给你一个下标从 0 开始的整数数组 nums 。如果 i 且 j - i != nums[j] - nums[i] ,那么我们称 (i, j) 是一个 坏 数对 。 请你返回 nums 中 坏数对 的总数目。 示例 1: 输入: nums = [4,1,3,3] 输出: 5 解释: 数对 (0, 1…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

根据题目描述,我们可以得知,对于任意的 $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 AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 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
lightbulb

解题思路

方法一:式子转换 + 哈希表

根据题目描述,我们可以得知,对于任意的 i<ji \lt j,如果 jinums[j]nums[i]j - i \neq \textit{nums}[j] - \textit{nums}[i],则 (i,j)(i, j) 是一个坏数对。

我们可以将式子转换为 inums[i]jnums[j]i - \textit{nums}[i] \neq j - \textit{nums}[j]。这启发我们用哈希表 cntcnt 来统计 inums[i]i - \textit{nums}[i] 的出现次数。

遍历数组,对于当前元素 nums[i]\textit{nums}[i],我们将 icnt[inums[i]]i - cnt[i - \textit{nums}[i]] 加到答案中,然后将 inums[i]i - \textit{nums}[i] 的出现次数加 11

最后,我们返回答案即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

统计坏数对的数目题解:数组·哈希·扫描 | LeetCode #2364 中等