美文网首页
Trapping Rain Water

Trapping Rain Water

作者: Wenyue_offer | 来源:发表于2017-09-13 11:43 被阅读0次

链接

class Solution {
    public int trap(int[] height) {
        int left = 0, right = height.length-1;
        int res = 0;
        // 左边大于右边,说明走过头了
        if(left>=right) return res;
        
        int leftheight = height[left];
        int rightheight = height[right];

        //two pointers问题,那边矮,移动哪边
        while(left<right){
            if(leftheight<rightheight){
                left ++;
                if(leftheight > heights[left]){
                    res += (leftheight -heights[left]);
                }else{
                    leftheight = height[left];
                }
            }else{
                right --;
                if(rightheight>heights[right]){
                    res += (rightheight-heights[right]);
                }else{
                    rightheight = heights[right];
                }
            }
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:Trapping Rain Water

      本文链接:https://www.haomeiwen.com/subject/dlpksxtx.html