【LeetCode】769. 最多能完成排序的块

769. 最多能完成排序的块(中等)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

方法一:贪心

思路

由于arr是[0,..., n-1] 的一个排列,若已遍历过的数中的最大值 max 与当前遍历到的下标相等,说明可以进行一次分割,累加答案。

代码

class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {
        int n = arr.size();
        int ans = 0, max = -1;
        for(int i=0, j=0; i<n; i++){
            if(arr[i] > max){
                max = arr[i];
            }
            if(max == i){
                max = -1;
                ans ++;
            }
            
        }
        return ans;
    }
};

方法二:单调栈

思路

  • 方法一的解法有一定的局限性,若数组中存在重复元素,就无法得到正确的答案。
  • 根据题目,我们可以发现,从左到右,每个分块都有一个最大值,并且这些分块的最大值呈单调递增。我们可以用一个来存储这些分块的最大值。最后得到的栈的大小,也就是题目所求的最多能完成排序的块
  • 这种解法,不仅可以解决本题,也可以解决“768.最多能完成排序的块”这道困难题(内部实现代码与本题完全一致)。

代码

class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {
        stack<int> st;
        for(int a : arr){
            if(st.empty() || a >= st.top()){
                st.push(a);
            }
            else if(!st.empty() && a < st.top()){
                int head = st.top();
                while(!st.empty() && a < st.top()){
                    st.pop();
                }
                st.push(head);
            }
        }
        return st.size();
    }
};

参考题解

  1. [Python3/Java/C++/Go] 一题双解:贪心 + 一次遍历 & 单调栈
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>