Leetcode 769. Max Chunks To Make Sorted

题目

链接:https://leetcode.com/problems/max-chunks-to-make-sorted/

**Level: ** Medium

Discription:
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.

Note:

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

代码1

class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {
        int max=-1,leftpos=-1,min=11,rightpos=11;
        int ret=0;
        bool flag = true;
        for(int i=0;i<arr.size();i++)
        {
            if(arr[i] > max)
                max = arr[i];
            if(arr[i] < min)
                min = arr[i];
            if(flag)
            {
                leftpos = i;
                rightpos = i;
                flag = false;
            }
            else
                rightpos++;
            if(max == rightpos && min == leftpos)
            {
                ret++;
                flag = true;
                max = -1;
                min = 11;
            }
        }
        return ret; 
    }
};

代码2

class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {
        int sum = 0,ret = 0;
        for(int i=0;i<arr.size();i++)
        {
            sum += arr[i]-i;
            if(sum == 0)
                ret++;
        }
        return ret;  
    }
};

思考

  • 算法时间复杂度为O(n),空间复杂度为O(1)。
  • 代码1记录最大值和最小值的值,当出现最大值等于块右侧的坐标,最小值等于块左侧的坐标时,说明此块排序可以形成整个有序队列的一个子队列。代码2利用了有序对列和与坐标之和相等的规律,更加简单。这类题还是找规律尽可能想出时间复杂度和空间复杂度最小的方法,在此基础上想出最简单的写法。
posted @ 2019-01-08 13:07  我的小叮当  阅读(261)  评论(0编辑  收藏  举报