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利用了有序对列和与坐标之和相等的规律,更加简单。这类题还是找规律尽可能想出时间复杂度和空间复杂度最小的方法,在此基础上想出最简单的写法。
  • 相关阅读:
    会话技术——Cookie
    Servlet——Request和Response
    #Servlet——Web之间跳转和信息共享、三大作用域对象
    8个技巧教你区分LED灯具优劣
    建筑景观LED照明设计要考虑哪些?
    荧光材料物理特性对白光LED光输出冷热比的影响
    金刚战神D系列户外全彩D5.92
    2020爱你爱你,海佳集团祝您新年快乐!
    复制文本
    超市会员系统
  • 原文地址:https://www.cnblogs.com/zuotongbin/p/10238409.html
Copyright © 2011-2022 走看看