LeetCode 题解工作台

数组能形成多少数对

给你一个下标从 0 开始的整数数组 nums 。在一步操作中,你可以执行以下步骤: 从 nums 选出 两个 相等的 整数 从 nums 中移除这两个整数,形成一个 数对 请你在 nums 上多次执行此操作直到无法继续执行。 返回一个下标从 0 开始、长度为 2 的整数数组 answer 作为答案,…

category

3

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以统计数组 中每个数字 出现的次数,记录在哈希表或数组 中。 然后遍历 ,对于每个数字 ,如果 出现的次数 大于 ,则可以从数组中选出两个 形成一个数对,我们将 除以 向下取整,即可得到当前数字 可以形成的数对数目,然后我们累加这个数目到变量 中。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums 。在一步操作中,你可以执行以下步骤:

  • nums 选出 两个 相等的 整数
  • nums 中移除这两个整数,形成一个 数对

请你在 nums 上多次执行此操作直到无法继续执行。

返回一个下标从 0 开始、长度为 2 的整数数组 answer 作为答案,其中 answer[0] 是形成的数对数目,answer[1] 是对 nums 尽可能执行上述操作后剩下的整数数目。

 

示例 1:

输入:nums = [1,3,2,1,3,2,2]
输出:[3,1]
解释:
nums[0] 和 nums[3] 形成一个数对,并从 nums 中移除,nums = [3,2,3,2,2] 。
nums[0] 和 nums[2] 形成一个数对,并从 nums 中移除,nums = [2,2,2] 。
nums[0] 和 nums[1] 形成一个数对,并从 nums 中移除,nums = [2] 。
无法形成更多数对。总共形成 3 个数对,nums 中剩下 1 个数字。

示例 2:

输入:nums = [1,1]
输出:[1,0]
解释:nums[0] 和 nums[1] 形成一个数对,并从 nums 中移除,nums = [] 。
无法形成更多数对。总共形成 1 个数对,nums 中剩下 0 个数字。

示例 3:

输入:nums = [0]
输出:[0,1]
解释:无法形成数对,nums 中剩下 1 个数字。

 

提示:

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

解题思路

方法一:计数

我们可以统计数组 nums\textit{nums} 中每个数字 xx 出现的次数,记录在哈希表或数组 cnt\textit{cnt} 中。

然后遍历 cnt\textit{cnt},对于每个数字 xx,如果 xx 出现的次数 vv 大于 11,则可以从数组中选出两个 xx 形成一个数对,我们将 vv 除以 22 向下取整,即可得到当前数字 xx 可以形成的数对数目,然后我们累加这个数目到变量 ss 中。

最后剩余的个数为数组 nums\textit{nums} 的长度减去可以形成的数对数目乘以 22,即 ns×2n - s \times 2

答案为 [s,ns×2][s, n - s \times 2]

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nn 为数组 nums\textit{nums} 的长度;而 CC 为数组 nums\textit{nums} 中数字的范围,本题中 C=101C = 101

1
2
3
4
5
6
class Solution:
    def numberOfPairs(self, nums: List[int]) -> List[int]:
        cnt = Counter(nums)
        s = sum(v // 2 for v in cnt.values())
        return [s, len(nums) - s * 2]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate identify the necessity of counting frequencies to determine pairs?

  • question_mark

    How well does the candidate handle hashing and array scanning in their solution?

  • question_mark

    Is the candidate aware of how to efficiently calculate leftovers after pairing?

warning

常见陷阱

外企场景
  • error

    Overlooking the need to count frequencies before trying to form pairs.

  • error

    Forgetting to account for leftover integers after forming pairs.

  • error

    Not using a hash table or efficient data structure for counting, which leads to poor performance.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the array contains negative numbers?

  • arrow_right_alt

    How would the solution change if duplicates can be paired multiple times?

  • arrow_right_alt

    What if we are asked to find pairs with different conditions, such as pairs whose sum equals a target?

help

常见问题

外企场景

数组能形成多少数对题解:数组·哈希·扫描 | LeetCode #2341 简单