LeetCode 题解工作台
将数组划分成相等数对
给你一个整数数组 nums ,它包含 2 * n 个整数。 你需要将 nums 划分成 n 个数对,满足: 每个元素 只属于一个 数对。 同一数对中的元素 相等 。 如果可以将 nums 划分成 n 个数对,请你返回 true ,否则返回 false 。 示例 1: 输入: nums = [3,2,…
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
根据题目描述,只要数组中每个元素出现的次数都是偶数次,就可以将数组划分成 个数对。 因此,我们可以用一个哈希表或者数组 记录每个元素出现的次数,然后遍历 ,如果有任何一个元素出现的次数是奇数次,就返回 ,否则返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 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 * n1 <= n <= 5001 <= nums[i] <= 500
解题思路
方法一:计数
根据题目描述,只要数组中每个元素出现的次数都是偶数次,就可以将数组划分成 个数对。
因此,我们可以用一个哈希表或者数组 记录每个元素出现的次数,然后遍历 ,如果有任何一个元素出现的次数是奇数次,就返回 ,否则返回 。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def divideArray(self, nums: List[int]) -> bool:
cnt = Counter(nums)
return all(v % 2 == 0 for v in cnt.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.