[Leetcode] 768. Max Chunks To Make Sorted II 解题报告

本文介绍了LeetCode第768题的解题报告,探讨如何将数组分割成多个部分并排序,以得到排序后的数组。通过分析,提出了一种在O(n)时间和O(n)空间复杂度内的解决方案,利用额外数组记录右侧最小值,从左到右扫描以确定最大可能的切块数。
摘要由CSDN通过智能技术生成

题目

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].

思路

通过观察可知,如果在某个位置,左边最大的数比右边最小的数都大,那么说明就需要新分割出来一个chunk了。为了在线性时间复杂度内解决问题,我们额外定义一个数组right_min,其中right_min[i]表示在i的右边(包含i本身)的最小数。然后从左到右扫描数组,并记录截止当前的最大数。如果一旦发现其左边的最大数要大于等于右边的最小数,就新开始一个chunk(当然此时还需要更新left_max的值)。

算法的时间复杂度是O(n),空间复杂度也是O(n)。

代码

class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {
        int n = arr.size();
        vector<int> right_min(n, 0);            // right_min[i] means the min value to its right
        right_min[n - 1] = arr[n - 1];
        for( int i = n - 2; i >= 0; --i) {
            right_min[i] = min(arr[i], right_min[i+1]);
        }
        int ans = 1, left_max = arr[0];
        for (int i = 1; i < n; ++i) {
            if (right_min[i] < left_max) {      // the right side has small value(s), hence cannot split
                left_max = max(left_max, arr[i]);
            }
            else {
                ++ans;
                left_max = arr[i];
            }
        }
        return ans;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值