[leetcode] 769. Max Chunks To Make Sorted

网友投稿 292 2022-08-27

[leetcode] 769. Max Chunks To Make Sorted

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: 1Explanation: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: 4Explanation: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& arr) { int res=0; int n=arr.size(); for(int i=0;i=arr.back()){ return res+1; } } i=j-1; res++; } return res; }};

参考文献

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:被中消协点名后仍“顶风作案”,肯德基成也营销困也营销?
下一篇:[leetcode] 149. Max Points on a Line
相关文章

 发表评论

暂时没有评论,来抢沙发吧~