[双指针] leetcode 42 Trapping Rain Water

problem:https://leetcode.com/problems/trapping-rain-water/

       此题需要维护首尾两个指针,每次移动较小高度处的指针。

       同时,维护左右的最大高度,作为当前可装水的高度。每次更新较小高度处的装水量,因为当前位置高度比另一侧更小,起码可以保证水不会从另一边漏出来。

class Solution {
public:
    int trap(vector<int>& height) {
        int left = 0;
        int right = height.size() - 1;
        int res = 0;
        int maxleft = 0;
        int maxright = 0;
        while(left <= right)
        {
            maxleft = max(maxleft, height[left]);
            maxright = max(maxright, height[right]);
            if(height[left] <= height[right])
            {
                if(height[left] < maxleft) 
                {
                    res += maxleft - height[left];
                }
                left++;
            }
            else
            {
                if(height[right] < maxright) 
                {
                    res += maxright - height[right];
                }
                right--;
            }
            
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11299971.html