LeetCode 题解工作台
最多能完成排序的块
给定一个长度为 n 的整数数组 arr ,它表示在 [0, n - 1] 范围内的整数的排列。 我们将 arr 分割成若干 块 (即分区),并对每个块单独排序。将它们连接起来后,使得连接的结果和按升序排序后的原数组相同。 返回数组能分成的最多块数量。 示例 1: 输入: arr = [4,3,2,1…
5
题型
7
代码语言
3
相关题
当前训练重点
中等 · 栈·状态
答案摘要
由于 是 的一个排列,若已遍历过的数中的最大值 与当前遍历到的下标 相等,说明可以进行一次分割,累加答案。 时间复杂度 ,空间复杂度 。其中 为数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给定一个长度为 n 的整数数组 arr ,它表示在 [0, n - 1] 范围内的整数的排列。
我们将 arr 分割成若干 块 (即分区),并对每个块单独排序。将它们连接起来后,使得连接的结果和按升序排序后的原数组相同。
返回数组能分成的最多块数量。
示例 1:
输入: arr = [4,3,2,1,0] 输出: 1 解释: 将数组分成2块或者更多块,都无法得到所需的结果。 例如,分成 [4, 3], [2, 1, 0] 的结果是 [3, 4, 0, 1, 2],这不是有序的数组。
示例 2:
输入: arr = [1,0,2,3,4] 输出: 4 解释: 我们可以把它分成两块,例如 [1, 0], [2, 3, 4]。 然而,分成 [1, 0], [2], [3], [4] 可以得到最多的块数。 对每个块单独排序后,结果为 [0, 1], [2], [3], [4]
提示:
n == arr.length1 <= n <= 100 <= arr[i] < narr中每个元素都 不同
解题思路
方法一:贪心 + 一次遍历
由于 是 的一个排列,若已遍历过的数中的最大值 与当前遍历到的下标 相等,说明可以进行一次分割,累加答案。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
mx = ans = 0
for i, v in enumerate(arr):
mx = max(mx, v)
if i == mx:
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Ability to utilize stack-based algorithms for array manipulation.
- question_mark
Efficient handling of greedy problems, ensuring maximum chunks are found.
- question_mark
Understanding of time and space complexities in algorithm design.
常见陷阱
外企场景- error
Failing to account for the required sorted order when partitioning.
- error
Incorrectly managing chunk boundaries, leading to fewer chunks than possible.
- error
Overcomplicating the problem by trying to solve it with nested loops or recursion.
进阶变体
外企场景- arrow_right_alt
Implement a solution where sorting within chunks takes extra time.
- arrow_right_alt
Handle the case when the array is already sorted.
- arrow_right_alt
Optimize further for larger arrays (n > 10).