LeetCode 题解工作台

将数组划分成相等数对

给你一个整数数组 nums ,它包含 2 * n 个整数。 你需要将 nums 划分成 n 个数对,满足: 每个元素 只属于一个 数对。 同一数对中的元素 相等 。 如果可以将 nums 划分成 n 个数对,请你返回 true ,否则返回 false 。 示例 1: 输入: nums = [3,2,…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

根据题目描述,只要数组中每个元素出现的次数都是偶数次,就可以将数组划分成 个数对。 因此,我们可以用一个哈希表或者数组 记录每个元素出现的次数,然后遍历 ,如果有任何一个元素出现的次数是奇数次,就返回 ,否则返回 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,它包含 2 * n 个整数。

你需要将 nums 划分成 n 个数对,满足:

  • 每个元素 只属于一个 数对。
  • 同一数对中的元素 相等 。

如果可以将 nums 划分成 n 个数对,请你返回 true ,否则返回 false 。

 

示例 1:

输入:nums = [3,2,3,2,2,2]
输出:true
解释:
nums 中总共有 6 个元素,所以它们应该被划分成 6 / 2 = 3 个数对。
nums 可以划分成 (2, 2) ,(3, 3) 和 (2, 2) ,满足所有要求。

示例 2:

输入:nums = [1,2,3,4]
输出:false
解释:
无法将 nums 划分成 4 / 2 = 2 个数对且满足所有要求。

 

提示:

  • nums.length == 2 * n
  • 1 <= n <= 500
  • 1 <= nums[i] <= 500
lightbulb

解题思路

方法一:计数

根据题目描述,只要数组中每个元素出现的次数都是偶数次,就可以将数组划分成 nn 个数对。

因此,我们可以用一个哈希表或者数组 cnt\textit{cnt} 记录每个元素出现的次数,然后遍历 cnt\textit{cnt},如果有任何一个元素出现的次数是奇数次,就返回 false\textit{false},否则返回 true\textit{true}

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

1
2
3
4
5
class Solution:
    def divideArray(self, nums: List[int]) -> bool:
        cnt = Counter(nums)
        return all(v % 2 == 0 for v in cnt.values())
speed

复杂度分析

指标
时间complexity is O(n) because we scan nums once to build counts and then iterate over the hash map. Space complexity is O(n) due to the hash map storing frequencies of elements.
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect fast hashing to track occurrences for a simple O(n) solution.

  • question_mark

    Check for edge cases where some numbers appear an odd number of times.

  • question_mark

    Look for direct application of array scanning plus hash lookup rather than sorting.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle odd frequencies correctly, which causes wrong true results.

  • error

    Assuming sorted pairing is needed, which adds unnecessary complexity.

  • error

    Ignoring the problem constraint that nums length is always even.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Pair array elements into groups of k instead of 2, generalizing the hash counting approach.

  • arrow_right_alt

    Determine if all elements can be paired when allowed to swap any numbers arbitrarily.

  • arrow_right_alt

    Return the actual pairs formed instead of only a boolean, still using frequency counts.

help

常见问题

外企场景

将数组划分成相等数对题解:数组·哈希·扫描 | LeetCode #2206 简单