LeetCode 题解工作台
分割数组
给定一个数组 nums ,将其划分为两个连续子数组 left 和 right , 使得: left 中的每个元素都小于或等于 right 中的每个元素。 left 和 right 都是非空的。 left 的长度要尽可能小。 在完成这样的分组后返回 left 的 长度 。 用例可以保证存在这样的划分方…
1
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数组·driven
答案摘要
划分后的两个子数组要满足题目要求,需要保证“数组前缀最大值”小于等于“数组后缀最小值”。 因此,我们可以先预处理出数组的后缀最小值,记录在 `mi` 数组中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给定一个数组 nums ,将其划分为两个连续子数组 left 和 right, 使得:
left中的每个元素都小于或等于right中的每个元素。left和right都是非空的。left的长度要尽可能小。
在完成这样的分组后返回 left 的 长度 。
用例可以保证存在这样的划分方法。
示例 1:
输入:nums = [5,0,3,8,6] 输出:3 解释:left = [5,0,3],right = [8,6]
示例 2:
输入:nums = [1,1,1,0,6,12] 输出:4 解释:left = [1,1,1,0],right = [6,12]
提示:
2 <= nums.length <= 1050 <= nums[i] <= 106- 可以保证至少有一种方法能够按题目所描述的那样对
nums进行划分。
解题思路
方法一:前缀最大值 + 后缀最小值
划分后的两个子数组要满足题目要求,需要保证“数组前缀最大值”小于等于“数组后缀最小值”。
因此,我们可以先预处理出数组的后缀最小值,记录在 mi 数组中。
然后从前往后遍历数组,维护数组前缀的最大值 mx,当遍历到某个位置时,如果数组前缀最大值小于等于数组后缀最小值,那么当前位置就是划分的分界点,直接返回即可。
时间复杂度 ,空间复杂度 。其中 为数组 nums 的长度。
class Solution:
def partitionDisjoint(self, nums: List[int]) -> int:
n = len(nums)
mi = [inf] * (n + 1)
for i in range(n - 1, -1, -1):
mi[i] = min(nums[i], mi[i + 1])
mx = 0
for i, v in enumerate(nums, 1):
mx = max(mx, v)
if mx <= mi[i]:
return i
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Candidates should demonstrate proficiency with array-driven strategies and partitioning concepts.
- question_mark
Watch for clear reasoning in determining the partition point based on left and right subarray comparisons.
- question_mark
Efficient solutions with linear time complexity will be expected, especially for large input sizes.
常见陷阱
外企场景- error
Not maintaining the left subarray's maximum or the right subarray's minimum properly during iteration.
- error
Assuming the partition must be found at the first occurrence of an increasing element, without considering all array elements.
- error
Overcomplicating the problem by using nested loops or extra space when a simple linear scan is sufficient.
进阶变体
外企场景- arrow_right_alt
Modify the problem to partition based on a different condition, such as comparing the sum of left and right subarrays.
- arrow_right_alt
Extend the problem to support multiple partitions within the array, resulting in more than two subarrays.
- arrow_right_alt
Change the partition condition so that the left subarray contains elements strictly greater than the right subarray.