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.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6
题意:
给定一个数组,用来表示地形的海拔高度,假设相邻之间宽度为1,求出此地形在下雨时最多能够蓄水多少?
分析:
大致可以分为两种解题思路;i)逐个求出当前位置的蓄水量(蓄水量由相邻较高海拔与当前地形海拔的差决定),然后累加即可;ii)一次性计算出以当前海拔为下界的蓄水量,以此累加;实现分别如下:
Code1 i & C++
class Solution {
public:
int trap(vector<int>& height) {
std::ios::sync_with_stdio(false);
cin.tie(0);
int left=0, right=height.size()-1;
int left_max=0, right_max=0, ans=0;
while(left<right){
if(height[left]<height[right]){
height[left]>left_max?(left_max=height[left]):(ans+=left_max-height[left]);
++left;
}else{
height[right]>right_max?(right_max=height[right]):(ans+=right_max-height[right]);
--right;
}
}
return ans;
}
};
分别计算出当前海拔高度的蓄水量,然后累加。
Result:
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Trapping Rain Water.
Memory Usage: 9.1 MB, less than 99.63% of C++ online submissions for Trapping Rain Water.
Code1 & Python
class Solution:
def trap(self, height: List[int]) -> int:
left, right = 0, len(height)-1
leftMax, rightMax, ans = 0, 0, 0
while left<right:
if height[left]<height[right]:
if height[left]>leftMax:
leftMax = height[left]
else:
ans += leftMax - height[left]
left+=1
else:
if height[right] > rightMax:
rightMax = height[right]
else:
ans += rightMax - height[right]
right-=1
return ans
Result:
Runtime: 48 ms, faster than 78.25% of Python3 online submissions for Trapping Rain Water.
Memory Usage: 13.4 MB, less than 5.11% of Python3 online submissions for Trapping Rain Water.
Code2 & C++
class Solution {
public:
int trap(vector<int>& height) {
std::ios::sync_with_stdio(false);
cin.tie(0);
int idx=0, len = height.size();
if(len<3)return 0;
// k用来表示边界值, tmpH表示两个较高海拔之间的高地海拔(即无法蓄水的部分),sign表示从左到右还是从右到左
int r=idx+1, tmpH=0, sum=0, sign=1, k=len;
while(r!=k){
tmpH=0;
while(r!=k && height[r]<height[idx]){
tmpH+=height[r];
r+=sign;
}
if(r!=k){
sum += height[idx]*(sign*(r-idx)-1)-tmpH;
idx=r;
r+=sign;
}else{// 当遇到最高海拔时,遍历方向变为从右向左
k = idx-1;
idx=len;
r=idx-1;
sign=-1;
}
}
return sum;
}
};
Result:
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Trapping Rain Water.
Memory Usage: 9 MB, less than 100.00% of C++ online submissions for Trapping Rain Water.