題目
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;
}