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
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
题意如图,就是看能盛多少水。
做了大概20min,runtime14ms
大体思路还是双指针,一个在头一个在尾,同时有个能够判断让这两个指针移动的一个参数,还是挺像two sum这个题的。
如果左边指针比右边大,右边向左走,否则左边指针向右走,O(n)的时间复杂度完成。
class Solution {
public:
int trap(vector<int>& height) {
if (height.size()<3) return 0;
int res = 0, l = 0, n = height.size(), r = n - 1;
int mi = 0;
while (r > l)
{
mi =max(mi,min(height[l], height[r]));
if (height[l] >= height[r])
{
r--;
if (l == r) break;
if (height[r] < mi)
{
res += mi - height[r];
}
}
else
{
l++;
if (l == r) break;
if (height[l] < mi)
{
res += mi - height[l];
}
}
}
return res;
}
};