LeetCode 题解工作台

最多能完成排序的块

给定一个长度为 n 的整数数组 arr ,它表示在 [0, n - 1] 范围内的整数的排列。 我们将 arr 分割成若干 块 (即分区),并对每个块单独排序。将它们连接起来后,使得连接的结果和按升序排序后的原数组相同。 返回数组能分成的最多块数量。 示例 1: 输入: arr = [4,3,2,1…

category

5

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

由于 是 的一个排列,若已遍历过的数中的最大值 与当前遍历到的下标 相等,说明可以进行一次分割,累加答案。 时间复杂度 ,空间复杂度 。其中 为数组 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个长度为 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.length
  • 1 <= n <= 10
  • 0 <= arr[i] < n
  • arr 中每个元素都 不同
lightbulb

解题思路

方法一:贪心 + 一次遍历

由于 arr\textit{arr}[0,..,n1][0,..,n-1] 的一个排列,若已遍历过的数中的最大值 mx\textit{mx} 与当前遍历到的下标 ii 相等,说明可以进行一次分割,累加答案。

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nn 为数组 arr\textit{arr} 的长度。

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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).

help

常见问题

外企场景

最多能完成排序的块题解:栈·状态 | LeetCode #769 中等