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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- My code: reference:https://discuss.leetcode.com/topic/604...
- 【题目描述】 Givennxmnon-negative integers representing an elev...
- 【题目描述】 Givennnon-negative integers representing an elevat...
- 题目 Given n non-negative integers representing an elevatio...
- 这两道题的一个要点在于,由于柱子是有宽度的,所以有外向里时,仅里面高度低时才有可能灌水。所以我们compare 内...