题目
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.
思路
左右两边往中间逼近,比如左边第0个开始知道第一个,遇到的最大的是1,第二个为0,第二个可惜蓄水1个单位
测试用例
[0,1,0,2,1,0,1,3,2,1,2,1]
[]
[1]
[1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1]
代码
package leetcodeArray;
public class Leetcode42TrappingRainWater {
public int trap(int[] height){
if(height.length < 2)
return 0;
int left = 0, right = height.length - 1;
int leftMax = 0, rightMax = 0;
int rainWater = 0;
while(left <= right){
if(height[left] <= height[right]){
if(height[left] >= leftMax)
leftMax = height[left];
else
rainWater+= leftMax - height[left];
left++;
}
else{
if(height[right] >= rightMax)
rightMax = height[right];
else
rainWater += rightMax - height[right];
right--;
}
}
return rainWater;
}
}
结果
他山之玉
int trap(int* height, int n) {
int level = 0, water = 0;
while (n--) {
int lower = *height < height[n] ? *height++ : height[n];
if (lower > level) level = lower;
water += level - lower;
}
return water;
}
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;
}
};
public int trap(int[] A){
int a=0;
int b=A.length-1;
int max=0;
int leftmax=0;
int rightmax=0;
while(a<=b){
leftmax=Math.max(leftmax,A[a]);
rightmax=Math.max(rightmax,A[b]);
if(leftmax<rightmax){
max+=(leftmax-A[a]); // leftmax is smaller than rightmax, so the (leftmax-A[a]) water can be stored
a++;
}
else{
max+=(rightmax-A[b]);
b--;
}
}
return max;
}