Trapping Rain Water
2017-09-13 本文已影响0人
Wenyue_offer
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;
}
}