题目
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.- 解法1
分治法,O(n log n)。对于区间[l, r],如果max(height[l+1] … height[r-1]) > max(height[l], height[r]),那么res(l, r) = res(l, heighest_index) + res(heighest_index, r)。
class Solution {
int f(vector<int>& height, int l, int r) {
if (r - l <= 1)
return 0;
int Max = -1, id = 0;
for (int i = l + 1; i < r; i++) {
if (height[i] > Max) {
Max = height[i];
id = i;
}
}
if (Max <= height[l] && Max <= height[r]) {
int h = std::min(height[l], height[r]), ret = 0;
for (int i = l + 1; i < r; i++)
ret += std::max(0, h - height[i]);
return ret;
}
else {
return f(height, l, id) + f(height, id, r);
}
}
public:
int trap(vector<int>& height) {
int l = 0, r = (int)height.size() - 1;
return f(height, l, r);
}
};
- 解法2
O(n)复杂度。考虑一下,填满后的特点,一定是中间高两边低(边界情况是递增或者递减)。那么从两侧往中间扫描的时候,就可以知道当前位置的水位。
class Solution {
public:
int trap(vector<int>& height) {
int l = 0, r = (int)height.size() - 1, level = 0, ret = 0;
while (l < r) {
int lower = height[height[l] < height[r] ? l++ : r--];
level = std::max(level, lower);
ret += level - lower;
}
return ret;
}
};