解法一:动态规划(复杂度较高)
class Solution {
public int trap(int[] height) {
int n = height.length;
if (n == 0) {
return 0;
}
int[] leftMax = new int[n];
leftMax[0] = height[0];
for (int i = 1; i < n; ++i) {
leftMax[i] = Math.max(leftMax[i - 1], height[i]);
}
int[] rightMax = new int[n];
rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; --i) {
rightMax[i] = Math.max(rightMax[i + 1], height[i]);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return ans;
}
}
解法二:双指针
class Solution {
public int trap(int[] height) {
int result = 0;
int left = 0;
int right = height.length - 1;
int leftMax = 0, rightMax = 0;
while (left < right) {
leftMax = Math.max(leftMax, height[left]);
rightMax = Math.max(rightMax, height[right]);
//左边比右边低的时候,先把左边填满水,否则,填满右边
if (height[left] <= height[right]) {
result += leftMax - height[left];
++left;
} else {
result += rightMax - height[right];
--right;
}
}
return result;
}
}
来源:LeetCode官方