问题:
给一个[0~size()-1]排列的一个数组,我们将其最多分成几块,各自进行全排序,能得到整体有序的数列?
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].
解法:
第i位的数值恰好是i的时候,可单独作为一个块
而前n块,应该为0~n的排列,要确定n为多少,n为前n块的最大值。
一直找的index==最大值n的时候,为一个块。
同理,第i~j的块下,j为最大值,一直找到index==j的时候,必须为一块,进行全排列。
代码参考:
1 class Solution { 2 public: 3 int maxChunksToSorted(vector<int>& arr) { 4 int res=0, maxv=0; 5 for(int i=0; i<arr.size(); i++){ 6 maxv=max(maxv,arr[i]); 7 if(i==maxv){ 8 res++; 9 } 10 } 11 return res; 12 } 13 };