首页 > 代码库 > 42. Trapping Rain Water
42. Trapping Rain Water
https://leetcode.com/problems/trapping-rain-water/#/solutions
Here is my idea: instead of calculating area by height*width, we can think it in a cumulative way. In other words, sum water amount of each bin(width=1).
Search from left to right and maintain a max height of left and right separately, which is like a one-side wall of partial container. Fix the higher one and flow water from the lower part. For example, if current height of left is lower, we fill water in the left bin. Until left meets right, we filled the whole container.
左右指针、最大值维护、正序、逆序
class Solution { public: int trap(int A[], int n) { int left=0; int right=n-1; int res=0; int maxleft=0, maxright=0; while(left<=right){ if(A[left]<=A[right]){ if(A[left]>=maxleft) maxleft=A[left]; else res+=maxleft-A[left]; left++; } else{ if(A[right]>=maxright) maxright= A[right]; else res+=maxright-A[right]; right--; } } return res; } };
42. Trapping Rain Water
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。