• 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利用了有序对列和与坐标之和相等的规律,更加简单。这类题还是找规律尽可能想出时间复杂度和空间复杂度最小的方法,在此基础上想出最简单的写法。
  • 相关阅读:
    超轻量级三级展开列表
    5 Reasons Your Javascript Stinks
    xhEditor 轻量级文本编辑器简单配置
    简单SEO攻略
    ashx文件
    xml中xPath的使用
    关于MSDN,文章索引
    关于Jquery中 “$(document).ready(function(){ })”函数的使用
    在Jquery使用过程中用到了css属性:opacity(不透明度),cursor (光标的类型、形状)
    初识Silverlight
  • 原文地址:https://www.cnblogs.com/zuotongbin/p/10238409.html
Copyright © 2020-2023  润新知