[leetcode] 769. Max Chunks To Make Sorted

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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].

分析

题目的意思是:把一个数组切分成几份,然后分别排序,拼在一起使得原数组有序。问最多能够切成几份。

  • 分析例子1,这是一个倒序的数组,第一个数字是最大的,为4,那么我们想,这个数字4原本是应该位于数组的最后一个位置,所以中间不可能断开成新的块了,要不然数字4就没法跑到末尾去了。分析到这里,我们应该隐约有点感觉了,当前数字所在的块至少要到达坐标为当前数字大小的地方,比如数字4所在的块至少要包括i=4的那个位置。

  • 分析例子2。第一个数字是1,那么当前数字1所在的块至少要到 i=1 的位置,然后我们去 i=1 的位置上看,发现是数字0,并没有超过 i=1 的范围,那么前两个数就可以断开成一个新的块儿。再往后看,i=2 的位置是2,可以单独断开,后面的3和4也可以分别断开。

  • 我们遍历原数组,用cur表示能到达的最远点,然后我们遍历当前位置到cur之间的所有点,遍历的同时如果遇到更大的数字就更新cur,当cur大于等于末尾数字的时候,此时不能再拆分新块儿了,返回结果res加1。否则的话说明到达了最远点,更新第一个for循环的变量i,并且结果res自增1。

代码

class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {
        int res=0;
        int n=arr.size();
        for(int i=0;i<n;i++){
            int cur=arr[i];
            int j=i+1;
            for(;j<=cur;j++){
                cur=max(cur,arr[j]);
                if(cur>=arr.back()){
                    return res+1;
                }
            }
            i=j-1;
            res++;
        }
        return res;
    }
};

参考文献

[LeetCode] Max Chunks To Make Sorted 可排序的最大块数

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值