题目描述:
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.
Given [0,1,0,2,1,0,1,3,2,1,2,1]
,
return 6
.
这题的精髓在于:两根柱子能围多少水,是由最短的柱子决定的。根据这个,就不难想到用two pointers的方法,一根l指针在最左,一根r指针在最右,那么它们实际的valid height = min(heights[l], heights[r])。这个height是一个一直被维护的值:当heights[l] < heights[r]时,如果heights[l] < height,那就意味着l的地方可以蓄水,蓄水量为height - heights[l],此时height就不用更新,挪动l指针l++就可以进入下一轮; 如果heights[l] > height,那么此时无法蓄水,但是可以得到一个新的height = min(heights[l], heights[r]).当heights[l] >= heights[r]时,情况类似。
Mycode (AC = 33ms):
class Solution {
public:
/**
* @param heights: a vector of integers
* @return: a integer
*/
int trapRainWater(vector<int> &heights) {
// write your code here
if (heights.size() <= 2) {
return 0;
}
// l = 0, r = -1
int l = 0, r = heights.size() - 1;
int height = min(heights[l], heights[r]);
int water = 0, delta = 0;;
while (l < r) { // 1 vs. 3, height = 2, water = 2 + 2 + 1
if (heights[l] < heights[r]) {
delta = heights[l] < height?
height - heights[l] : 0; // 0
water += delta;
height = min(heights[r], max(heights[l], height)); // 2
l++;
}
else {
delta = heights[r] < height?
height - heights[r] : 0; // 0
water += delta;
height = min(heights[l], max(heights[r], height)); // height = 1
r--;
}
}
return water;
}
};