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利用了有序对列和与坐标之和相等的规律,更加简单。这类题还是找规律尽可能想出时间复杂度和空间复杂度最小的方法,在此基础上想出最简单的写法。

转载于:https://www.cnblogs.com/zuotongbin/p/10238409.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值