【数组】力扣769:最多能完成排序的块
给定一个长度为 n 的整数数组 arr ,它表示在 [0, n - 1] 范围内的整数的排列。
我们将 arr 分割成若干 块 (即分区),并对每个块单独排序。将它们连接起来后,使得连接的结果和按升序排序后的原数组相同。
返回数组能分成的最多块数量。
示例;
输入: arr = [1,0,2,3,4]
输出: 4
解释:
我们可以把它分成两块,例如 [1, 0], [2, 3, 4]。
然而,分成 [1, 0], [2], [3], [4] 可以得到最多的块数。
方法1:暴力解法
首先找到从左块开始最小块的大小。如果前 k 个元素为 [0, 1, ..., k-1],可以直接把他们分为一个块。当我们需要检查 [0, 1, ..., n-1] 中前 k+1 个元素是不是 [0, 1, ..., k] 的时候,只需要检查其中最大的数是不是 k 就可以了。
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
n = len(arr)
cur_max = 0 # 当前最大值 current maximum
ans = 0
for i in range(n):
cur_max = max(cur_max, arr[i])
if cur_max == i:
ans += 1
return ans
for循环可以采用enumerate函数来枚举数组中的数,则为
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
n = len(arr)
cur_max = ans = 0 # 当前最大值 current maximum 和 返回值均初始化为0
for i, num in enumerate(arr): # 改进
cur_max = max(cur_max, num)
if cur_max == i:
ans += 1
return ans

浙公网安备 33010602011771号