769. 最多能完成排序的块

53 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情

题目描述

给定一个长度为 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] 可以得到最多的块数。

提示:

n == arr.length
1 <= n <= 10
0 <= arr[i] < n
arr 中每个元素都 不同

解题思路

题目说数字的范围为【0,n-1】,那么把数组排序后,数组元素的值即为排序后的下标。我们遍历当前下标到maxIndex,只要有值大于maxIndex那么就需要更新maxIndex为大值,当执行到了maxIndex,那么ans就可以+1;以此类推,直到执行到maxIndex等于n为止。

比如[1,0,2,3,4]这个数组,第一次maxIndex = num[0] = 1, 那我们就需要遍历到下标1的位置处,遍历到下标1时,nums[1] = 0 < maxIndex,那第一次遍历结束。ans + 1 = 2了,第二次 maxIndex = nums[2] = 2,需要遍历到下标2,到下标2时nums[1] = 3,maxIndex = 3,遍历到下标3,nums[3] = 4了,遍历完成,ans=2.

代码

class Solution {
    public int maxChunksToSorted(int[] arr) {
        int n = arr.length;
        int maxIndex = 0;
        int i = 0;
        int ans = 0;
        while (i < n) {
            ans++;
            maxIndex = arr[i];
            for (int j = i; j <= maxIndex; j++) {
                maxIndex = Math.max(maxIndex, arr[j]);
            }
            i = maxIndex + 1;
        }
        return ans;
    }
}

image.png

总结

这道题的难点在于不断更新maxIndex的下标,只要有比maxIndex大的,那么就只能分为一组。