LeetCode 755. Pour Water

题目看着很吓人,实际就是模拟来做。

题目的意思其实是先看左边,每次找离k最近的局部最小值。左边不行才找右边,右边也不行就放在 heights[k]。

class Solution {
public:
    vector<int> pourWater(vector<int>& heights, int V, int index) {
        for (int k=0;k<V;++k){
            int left_idx=-1;
            for (int i=index-1;i>=0;--i){
                if (heights[i]>heights[i+1]) break;
                if (heights[i]<heights[i+1])
                    left_idx = i;
            }
            if (left_idx!=-1){
                heights[left_idx]++; 
                continue;
            }
            
            // cannot go left, so go right
            int right_idx=-1;
            for (int i=index+1;i<heights.size();++i){
                if (heights[i]>heights[i-1]) break;
                if (heights[i]<heights[i-1])
                    right_idx = i;
            }
            if (right_idx!=-1){
                heights[right_idx]++;
                continue;
            }
            heights[index]++;
        }
        return heights;
    }
};

 

posted @ 2018-11-11 04:46  約束の空  阅读(420)  评论(0)    收藏  举报