zoukankan      html  css  js  c++  java
  • 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利用了有序对列和与坐标之和相等的规律,更加简单。这类题还是找规律尽可能想出时间复杂度和空间复杂度最小的方法,在此基础上想出最简单的写法。
  • 相关阅读:
    Freemarker list的使用
    Java通过流对MP4视频文件进行加密,H5 video播放流
    阿里云API公共参数的获取
    javah找不到类文件
    Java调用打印机打印指定路径图片
    Java绘制图片并进行合成
    Java生成二维码和解析二维码URL
    计算机网络第六版知识大纲
    Linux安装mysql mysql5.5.40 <NIOT>
    rsync unison+inotify双向实时同步
  • 原文地址:https://www.cnblogs.com/zuotongbin/p/10238409.html
Copyright © 2011-2022 走看看