题目地址:https://leetcode-cn.com/problems/trapping-rain-water/description/
思路:刚开始我想一段一段的遍历过去求和,要考虑的情况较多,实现起来也比较复杂, 对每一个柱子能存多少水求和比较简单,
这样只需要获取这个柱子左边的最高高度和这个柱子右边的最高高低,2者的最小值就是这个柱子的存水量
AC代码1:
class Solution {
public int trap(int[] height) {
int sum = 0;
for (int i = 0; i < height.length; i++) {
int maxLeft = 0, maxRight = 0;
for (int left = 0; left < i; left++) {
maxLeft = Math.max(maxLeft, height[left]);
}
for (int right = i + 1; right < height.length ; right++) {
maxRight = Math.max(maxRight, height[right]);
}
int temp = Math.min(maxLeft, maxRight) - height[i];
if (temp > 0)
sum += temp;
}
return sum;
}
}
每次都要算某个柱子的左右最值,算法复杂度是O(n2),能不能把算左右最值的效率提高呢?这就用到动态规划了,假如说
我们用函数f(n),表示到第n个柱子(包括第n个柱子)左边的最大值,则f(n)=max(f(n-1),height[n]),其中height[n]为第n个柱子的高度,右边同理
AC代码2:
class Solution {
public int trap(int[] height) {
int sum = 0;
int len = height.length;
if (len == 0)
return 0;
int[] maxLeft = new int[len];
int[] maxRight = new int[len];
maxLeft[0] = height[0];
for (int i = 1; i < len; i++) {
maxLeft[i] = Math.max(height[i], maxLeft[i-1]);
}
maxRight[len - 1] = height[len - 1];
for (int i = len - 2; i >= 0; i--) {
maxRight[i] = Math.max(height[i] ,maxRight[i+1]);
}
for (int i = 0; i < height.length; i++) {
sum += Math.min(maxLeft[i], maxRight[i]) - height[i];
}
return sum;
}
}
官方题解:https://leetcode.com/articles/trapping-rain-water/#approach-1-brute-force-accepted