zoukankan      html  css  js  c++  java
  • LeetCode 768. Max Chunks To Make Sorted II

    原题链接在这里:https://leetcode.com/problems/max-chunks-to-make-sorted-ii/

    题目:

    This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8.


    Given an array arr of integers (not necessarily distinct), 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 = [5,4,3,2,1]
    Output: 1
    Explanation:
    Splitting into two or more chunks will not return the required result.
    For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
    

    Example 2:

    Input: arr = [2,1,3,4,4]
    Output: 4
    Explanation:
    We can split into two chunks, such as [2, 1], [3, 4, 4].
    However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
    

    Note:

    • arr will have length in range [1, 2000].
    • arr[i] will be an integer in range [0, 10**8].

    题解:

    We want to find the lines where all the values on line's left are smaller or equal to all the values on line's right.

    Once we have the count of such lines, the chunks number is lines count + 1.

    Then how to find such lines. We could track maximum from left and minimum from right and left maximimum <= right minimum, then there is such a line.

    Time Complexity: O(n). n = arr.length.

    Space: O(1).

    AC Java:

     1 class Solution {
     2     public int maxChunksToSorted(int[] arr) {
     3         int n = arr.length;
     4         int [] leftMax = new int[n];
     5         int [] rightMin = new int[n];
     6         int max = Integer.MIN_VALUE;
     7         for(int i = 0; i<n; i++){
     8             max = Math.max(max, arr[i]);
     9             leftMax[i] = max;
    10         }
    11         
    12         int min = Integer.MAX_VALUE;
    13         for(int i = n-1; i>=0; i--){
    14             min = Math.min(min, arr[i]);
    15             rightMin[i] = min;
    16         }
    17         
    18         int res = 0;
    19         for(int i = 0; i<n-1; i++){
    20             if(leftMax[i]<=rightMin[i+1]){
    21                 res++;
    22             }
    23         }
    24         
    25         return res + 1;
    26     }
    27 }
  • 相关阅读:
    当 IDENTITY_INSERT 设置为 OFF 时,不能向表 'tb_User' 中的标识列插入显式值。
    版本控制器Vss和svn
    判断浏览器刷新与关闭的代码
    web开发过程中要注意的问题(二)【转】
    JS版include函数
    兼容FF/IE的添加收藏夹的代码
    jQuery技巧总结
    把JS与CSS写在同一个文件里
    CSS hack浏览器兼容一览表
    利用JS获取IE客户端IP及MAC的实现
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11367324.html
Copyright © 2011-2022 走看看