LeetCode 769——Max Chunks To Make Sorted

Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

Example 1:

Input: arr = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.

Example 2:

Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.

Note:

  • arr will have length in range [1, 10].
  • arr[i] will be a permutation of [0, 1, ..., arr.length - 1].

 


 

我在理解这道题的题意上花费了一些时间,看来英语读不懂、学不会的难题还是要克服啊~

arr数组是一个由[0, 1, 2, ... , arr.length - 1]元素组成的序列,我们将它分成多个块,并将多个块单独排序后组合,使组合的结果与数组升序排列的结果相同。

求我们可以划分的最多的块是多少个?

 

题意明白后其实解题就不难了,虽然需要划分多个块,但是通过我们对示例的观察,有两个重要线索:

  • 尽量让每个数字分为一个块是最多的拆分方法。
  • 块划分之后的顺序是不能改变的,那么其实就是保证块内某数字排序之后对应的位置与数组中该数字排序后对应的位置相同。

所以一个块内最大的数字就是这个块对应的右边界。

这样说还是有点抽象,可以结合下边的示例感受一下:

示例

到5和6的时候的步骤省略掉了,因为5 6 的位置就是正确的,所以它们每个数字都可以单独分为一个块,最后划分的结果为:

[2, 4, 3, 1, 0], [5], [6]

 

我的原始代码和上边的思路是相同的,但是对于chunkNum何时加一的处理不一样,所以chunkNum的初始值也是不同的。

 


 

AC代码:

class Solution {
    public int maxChunksToSorted(int[] arr) {
        int arrLen = arr.length;
        int maxIndex = 0, result = 1;
        for (int i = 0; i < arrLen; ++i) {
            if (maxIndex < i) {
                ++result;
            }
            if (arr[i] > maxIndex) {
                maxIndex = arr[i];
            }
        }

        return result;
    }
}

 


如有错误,欢迎指摘。也欢迎通过左上角的“向TA提问”按钮问我问题,我将竭力解答你的疑惑。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值