Trapping Rain Water_Leetcode_#42

来源:互联网 发布:淘宝账期延长怎么解除 编辑:程序博客网 时间:2024/05/16 09:20

1 题目
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6

2 解法

public class Solution {    public int trap(int[] height) {        int lhs = 0, rhs = height.length - 1;         int max = 0, maxLeft = 0, maxRight = 0;        while(lhs < rhs){            if(height[lhs] < height[rhs]){                if(height[lhs] > maxLeft){                    maxLeft = height[lhs];                }else{                    max += maxLeft - height[lhs];                   }                ++lhs;            }else{                if(height[rhs] > maxRight){                    maxRight = height[rhs];                }else{                    max += maxRight - height[rhs];                }                --rhs;            }        }        return max;    }}
0 0
原创粉丝点击