LeetCode 题解工作台

好数对的数目

给你一个整数数组 nums 。 如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i j ,就可以认为这是一组 好数对 。 返回好数对的数目。 示例 1: 输入: nums = [1,2,3,1,1,3] 输出: 4 解释: 有 4 组好数对,分别是 (0,3), (0,4)…

category

4

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

遍历数组,对于每个元素 ,计算 之前有多少个元素与其相等,即为 与之前元素组成的好数对的数目。遍历完数组后,即可得到答案。 时间复杂度 ,空间复杂度 。其中 为数组长度,而 为数组中元素的取值范围。本题中 $C = 101$。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums

如果一组数字 (i,j) 满足 nums[i] == nums[j]i < j ,就可以认为这是一组 好数对

返回好数对的数目。

 

示例 1:

输入:nums = [1,2,3,1,1,3]
输出:4
解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始

示例 2:

输入:nums = [1,1,1,1]
输出:6
解释:数组中的每组数字都是好数对

示例 3:

输入:nums = [1,2,3]
输出:0

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
lightbulb

解题思路

方法一:计数

遍历数组,对于每个元素 xx,计算 xx 之前有多少个元素与其相等,即为 xx 与之前元素组成的好数对的数目。遍历完数组后,即可得到答案。

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nn 为数组长度,而 CC 为数组中元素的取值范围。本题中 C=101C = 101

1
2
3
4
5
6
7
8
9
class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        ans = 0
        cnt = Counter()
        for x in nums:
            ans += cnt[x]
            cnt[x] += 1
        return ans
speed

复杂度分析

指标
时间complexity is O(n) due to a single pass through the array and hash operations. Space complexity is O(k) where k is the number of unique elements in nums, bounded by 100 per constraints.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you recognize a counting or frequency pattern here?

  • question_mark

    Consider using a hash map to avoid nested loops.

  • question_mark

    Ask yourself if you can calculate pairs without generating them explicitly.

warning

常见陷阱

外企场景
  • error

    Double-counting pairs by iterating over all i < j combinations.

  • error

    Forgetting that i must be less than j, not just matching values.

  • error

    Using nested loops unnecessarily instead of leveraging hash counts.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count good pairs where i > j instead of i < j, adjusting logic accordingly.

  • arrow_right_alt

    Determine number of good triplets (i < j < k) with equal values using extended frequency counting.

  • arrow_right_alt

    Compute good pairs under a modulo constraint on the values to test handling of hash keys.

help

常见问题

外企场景

好数对的数目题解:数组·哈希·扫描 | LeetCode #1512 简单