LeetCode 题解工作台
分割数组
给你一个长度为 偶数 的整数数组 nums 。你需要将这个数组分割成 nums1 和 nums2 两部分,要求: nums1.length == nums2.length == nums.length / 2 。 nums1 应包含 互不相同 的元素。 nums2 也应包含 互不相同 的元素。 如果…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
根据题意,我们需要将数组分成两部分,每部分的元素都是互不相同的。因此,我们可以统计数组中每个元素的出现次数,如果某个元素出现的次数大于等于 次,那么就无法满足题意。否则,我们可以将数组分成两部分。 时间复杂度 ,空间复杂度 。其中 是数组的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个长度为 偶数 的整数数组 nums 。你需要将这个数组分割成 nums1 和 nums2 两部分,要求:
nums1.length == nums2.length == nums.length / 2。nums1应包含 互不相同 的元素。nums2也应包含 互不相同 的元素。
如果能够分割数组就返回 true ,否则返回 false 。
示例 1:
输入:nums = [1,1,2,2,3,4] 输出:true 解释:分割 nums 的可行方案之一是 nums1 = [1,2,3] 和 nums2 = [1,2,4] 。
示例 2:
输入:nums = [1,1,1,1] 输出:false 解释:分割 nums 的唯一可行方案是 nums1 = [1,1] 和 nums2 = [1,1] 。但 nums1 和 nums2 都不是由互不相同的元素构成。因此,返回 false 。
提示:
1 <= nums.length <= 100nums.length % 2 == 01 <= nums[i] <= 100
解题思路
方法一:计数
根据题意,我们需要将数组分成两部分,每部分的元素都是互不相同的。因此,我们可以统计数组中每个元素的出现次数,如果某个元素出现的次数大于等于 次,那么就无法满足题意。否则,我们可以将数组分成两部分。
时间复杂度 ,空间复杂度 。其中 是数组的长度。
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
return max(Counter(nums).values()) < 3
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) to scan and count all numbers, plus O(n) to assign duplicates, giving overall O(n). Space complexity is O(n) for the hash map storing counts. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expecting hash map or frequency array to track occurrences.
- question_mark
Checking if any number occurs more than twice hints at early termination.
- question_mark
Distribution of duplicates across two arrays shows understanding of distinct set formation.
常见陷阱
外企场景- error
Failing to immediately reject arrays with a number occurring more than twice.
- error
Assuming any even-length array can be split without checking frequencies.
- error
Overcomplicating the distribution instead of assigning one duplicate to each array.
进阶变体
外企场景- arrow_right_alt
Split array into k parts with distinct elements instead of just two.
- arrow_right_alt
Return one possible valid split instead of just true or false.
- arrow_right_alt
Handle arrays with negative numbers or larger ranges requiring generalized hash counting.