[Bis pointer] leetcode 42 Trapping Rain Water

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

       This question needs to maintain two pointers head and tail, the smaller each time you move the pointer at the height.

       At the same time, maintaining maximum height is about as highly currently filled with water. Each update means water at a small height, because the current position of a height smaller than the other side, the other side at least, ensure that water does not leak.

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;
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11299971.html