码迷,mamicode.com
首页 > 其他好文 > 详细

769. Max Chunks To Make Sorted

时间:2018-04-30 16:44:36      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:code   return   res   turn   pos   main   style   sort   bsp   

class Solution {
public:
    // O(n)
    // The idea is to maintain a window for all chars seen so far.
    // For [1,0,2,3,4], i = 0, we know the window should at least end on pos[i=0]=1.
    // For [4,3,2,1,0], i = 0, we know the window should at least end on pos[i=0]=4.
    // Then we move to next char in original string, and extend the window if necessary, 
    // until i==w. So then we need to move to next window.
    // We don‘t need to maintain the window start position.
    int maxChunksToSorted(vector<int>& arr) {
        int w = 0, res = 0;
        for (int i = 0; i < arr.size(); i++) {
            w = max(w, arr[i]);
            if (i == w) {
                res++;
                w = i+1;
            }
        }
        return res;
    }
};

 

769. Max Chunks To Make Sorted

标签:code   return   res   turn   pos   main   style   sort   bsp   

原文地址:https://www.cnblogs.com/JTechRoad/p/8973730.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!