*LeetCode-Trapping Rain Water

感觉很难想到 两个指针从两边 两边也都keep一个max 每次只挪动一个 根据当前那个低 就挪动那个 为了两个指针相遇的时候不会有冲突 而且相遇的时候也是低的一边决定水位

然后被挪动的一边判断当前高度和这边max的值 假如更高了 就update max, 否则就填一部分 填的是当前高度这个unit的上面和相应这边max之间的水

public class Solution {
    public int trap(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int maxLeft = 0;
        int maxRight = 0;
        int res = 0;
        while ( left <= right ){
            if ( height [left] <= height [right] ){
                if ( height[ left ] > maxLeft )
                    maxLeft = height [ left ];
                else
                    res += maxLeft - height[left];
                left ++;
            }
            else {
                if ( height [ right ] > maxRight )
                    maxRight = height [ right ];
                else 
                    res += maxRight - height[right];
                right --;
            }
        }
        return res;
        
    }
}

还有一个办法是用stack 并没有研究明白


你可能感兴趣的:(*LeetCode-Trapping Rain Water)