LeetCode 热题 100打卡第六天
接雨水(LeeCode第42题)
给定 n
个非负整数表示每个宽度为 1
的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
解法一:
class Solution {
public int trap(int[] height) {
if (height.length == 1 || height.length == 0) return 0;
int res = 0;
int i = 0,j = 1;
for(; j < height.length;){
if(height[j] >= height[i]){
res += height[i] *(j - i);
for( ; i < j; i++){
res -= height[i];
}
}
j++;
}
if(i != j){
int temp = i;
for(i = height.length - 1, j = height.length - 2; j >= temp;){
if(height[i] <= height[j]){
res += height[i] * (i - j);
for(; i > j; i--){
res -= height[i];
}
}
j--;
}
}
return res;
}
}
解法二:(利用数组)
class Solution {
// 直接计算每个柱子能接多少水,需要初始化l,r数组保存距当前柱子左右两边的最大高度
public int trap(int[] height) {
int n = height.length, res = 0;
int[] l = new int[n + 1], r = new int[n + 1];
// 边界就是本身
l[0] = height[0];
r[n - 1] = height[n - 1];
for (int i = 1; i < n; i ++ ) {
l[i] = Math.max(l[i - 1], height[i]);
}
for (int i = n - 2; i >= 0; i -- ) {
r[i] = Math.max(r[i + 1], height[i]);
}
for (int i = 0; i < n; i ++ ) {
// 存水取决于相对较小的那个
res += Math.min(l[i], r[i]) - height[i];
}
return res;
}
}