题目:
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.
解法:双指针,分别从数组左右两端开始扫描,各找到第一个峰值(大于左右两个邻居的值),之后每次选择较小的值向内搜索,若小于峰值计算装水量,若大于则重新定义峰值,如此进行直到两个指针相遇。时间O(n)
class Solution {
public:
int trap(vector<int>& height) {
int ans = 0, l = 0, r = height.size() - 1, h = 0;
while (l < r && height[l] <= height[l + 1]) l++;
while (l < r && height[r - 1] >= height[r]) r--;
while (l < r) {
if (height[l] < height[r]) {
h = height[l];
while (l < r && height[l] <= h) {
ans += h - height[l];
l++;
}
} else {
h = height[r];
while (l < r && height[r] <= h) {
ans += h - height[r];
r--;
}
}
}
return ans;
}
};
Runtime: 15 ms