給定 n 個非負整數表示每個寬度爲 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。
上面是由數組 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)。 感謝 Marcos 貢獻此圖。
示例:
輸入: [0,1,0,2,1,0,1,3,2,1,2,1]
輸出: 6
解法1:對於位置i, 能存儲的雨水取決於向左掃描以及向右掃描中最大高度的較小的一個,開兩個數組存儲向左掃描以及向右掃描的最大高度。時間複雜度,空間複雜度均爲O(n)
int max(int x,int y) {
return x>y? x:y;
}
int min(int x,int y) {
return x<y? x:y;
}
int trap(int* height, int heightSize){
if(height==NULL||heightSize<=0) {
return 0;
}
int water=0;
int left[heightSize];
int right[heightSize];
left[0]=height[0];
right[heightSize-1]=height[heightSize-1];
// 位置i向左掃描的高度最大值
for (int i = 1; i < heightSize; i++)
{
left[i]=max(left[i-1],height[i]);
}
// 位置i向右掃描的高度最大值
for (int i = heightSize-2; i >=0; i--)
{
right[i]=max(right[i+1],height[i]);
}
for (int i = 0; i < heightSize; i++)
{
water+=min(left[i],right[i])-height[i];
}
return water;
}
解法2:雙指針法,時間複雜度O(n), 空間複雜度O(1)
int trap(int* height, int heightSize){
int water=0;
int left_index = 0;
int right_index = heightSize-1;
int left_max=0,right_max=0;
while(left_index<right_index) {
if(height[left_index]<height[right_index]) {
if(height[left_index]>left_max) {
left_max=height[left_index];
} else {
water+=left_max-height[left_index];
}
left_index++;
} else {
if(height[right_index]>right_max) {
right_max=height[right_index];
} else {
water+=right_max-height[right_index];
}
right_index--;
}
}
return water;
}