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.

给出一个数组[0,1, …, arr.length-1], 把这个数组分成块,每块单独排序,接起来之后要是一个升序的数组,问最多能分多少块。

思路:
因为是每块单独排序,所以较大的数字出现在前面时不能单独分块,比如[2,1],2出现在1前面,2不能单独分块,不然1就不能参与前面2这块的排序,2和1这两块排好序接起来以后是[2,1],不是升序的[1,2]

遍历数组,到一个数字时,要保证它前面比它小的数字都要出现过,才能在此处分成一块。
定义一个变量,表示到目前为止的最大值,如果最大值==当前index,就表示比当前数字小的都出现过(因为数字是0~arr.length-1),分块数++。

分块数初始化为0,从index=0开始遍历,而不是1,初始化为1的话中间必然会出现满足最大值==当前index的条件,会再次+1,如arr = [4,3,2,1,0]

    public int maxChunksToSorted(int[] arr) {
        int n = arr.length;
        int maxNum = 0;
        int result = 0;
        
        for(int i = 0; i < n; i++) {
            maxNum = Math.max(maxNum, arr[i]);
            if(maxNum == i) {
                result ++;
            }
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值