Max Chunks To Make Sorted

LeetCode 768. Max Chunks To Make Sorted I

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?

意思就是,对一个数组进行分组(不能交换元素顺序),分好组之后进行组内排序,连接之后得到的结果和直接对原数组排序的结果一致。问最多可以把数组分成几组?

这个回答 思路很清晰,复杂度为 $O(n)$

笔试碰到了一样的题目,自己只想到了找右边最小元素,却忘了和已成组的最大值进行比较

也学到了用栈来保存右侧最小元素的方法

/**
 * 来源:https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/167259/Two-Java-O(n)-Solutions-with-Explanation-min-array-and-stack
 */
public int maxChunksToSorted(int[] arr) {
    int n = arr.length;
    Stack<Integer> smallest = new Stack<Integer>();
    for (int i = n-1; i >= 0; i--) {
        if (smallest.isEmpty() || arr[i] <= smallest.peek())
            smallest.push(arr[i]);
    }
    int largest = arr[0];
    int ret = 0;
    for (int i = 0; i < n-1; i++) {
        if (arr[i] == smallest.peek())
            smallest.pop();
        largest = Math.max(largest, arr[i]);
        if (largest <= smallest.peek()) {
            ret++;
            largest = arr[i+1];
        }
    }
    return ret+1;
}

 类似的,也可以将右侧的最小值保存在一个数组里

 1 public int maxChunksToSorted(int[] arr) {
 2     int len = arr.length;
 3     int[] minRight = new int[len];
 4 
 5     int maxLeft = arr[0];
 6 
 7     minRight[len - 1] = arr[len - 1];
 8     for (int i = len - 2; i >= 0; i--) {
 9         minRight[i] = Math.min(minRight[i + 1], arr[i + 1]);
10     }
11 
12     int count = 1;
13     for (int i = 0; i < len - 1; i++) {
14         if (maxLeft <= minRight[i]) {
15             count++;
16         }
17         maxLeft = Math.max(maxLeft, arr[i + 1]);
18     }
19 
20     return count;
21 }

 

转载于:https://www.cnblogs.com/ainsliaea/p/11407551.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值