LeetCode 题解工作台
划分数组为连续数字的集合
给你一个整数数组 nums 和一个正整数 k ,请你判断是否可以把这个数组划分成一些由 k 个连续数字组成的集合。 如果可以,请返回 true ;否则,返回 false 。 示例 1: 输入: nums = [1,2,3,3,4,4,5,6], k = 4 输出: true 解释: 数组可以分成 […
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们首先判断数组 的长度是否能被 整除,如果不能整除,说明无法将数组划分成若干个长度为 的子数组,直接返回 。 接下来,我们用一个哈希表 统计数组 中每个数字出现的次数,然后对数组 进行排序。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums 和一个正整数 k,请你判断是否可以把这个数组划分成一些由 k 个连续数字组成的集合。
如果可以,请返回 true;否则,返回 false。
示例 1:
输入:nums = [1,2,3,3,4,4,5,6], k = 4 输出:true 解释:数组可以分成 [1,2,3,4] 和 [3,4,5,6]。
示例 2:
输入:nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3 输出:true 解释:数组可以分成 [1,2,3] , [2,3,4] , [3,4,5] 和 [9,10,11]。
示例 4:
输入:nums = [1,2,3,4], k = 3 输出:false 解释:数组不能分成几个大小为 3 的子数组。
提示:
1 <= k <= nums.length <= 1051 <= nums[i] <= 109
注意:此题目与 846 重复:https://leetcode.cn/problems/hand-of-straights/
解题思路
方法一:哈希表 + 排序
我们首先判断数组 的长度是否能被 整除,如果不能整除,说明无法将数组划分成若干个长度为 的子数组,直接返回 。
接下来,我们用一个哈希表 统计数组 中每个数字出现的次数,然后对数组 进行排序。
然后,我们遍历排序后的数组 ,对于每个数字 ,如果 不为 ,我们枚举 到 的每个数字 ,如果 为 ,说明无法将数组划分成若干个长度为 的子数组,直接返回 。否则,我们将 减 。
遍历结束后,说明可以将数组划分成若干个长度为 的子数组,返回 。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
if len(nums) % k:
return False
cnt = Counter(nums)
for x in sorted(nums):
if cnt[x]:
for y in range(x, x + k):
if cnt[y] == 0:
return False
cnt[y] -= 1
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log n) due to sorting or heap operations, where n is the array length. Hash map lookups for building and updating counts are O(1) each. Space complexity is O(n) to store frequency counts. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Asks if duplicates affect sequence formation
- question_mark
Checks understanding of greedy consecutive construction
- question_mark
Observes handling of gaps in the array sequence
常见陷阱
外企场景- error
Failing to decrement counts correctly for duplicates
- error
Assuming sorted array without handling missing numbers
- error
Using linear search instead of hash map, causing TLE for large n
进阶变体
外企场景- arrow_right_alt
Partition array into sets of k consecutive odd or even numbers
- arrow_right_alt
Allow sequences of length k but with at most one missing number
- arrow_right_alt
Return the actual groups instead of boolean result