Trapping Rain Water

Description:

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.

Example

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

Solution:

class Solution {
public:
	/**
	 * @param heights: a vector of integers
	 * @return: a integer
	 */
	int trapRainWater(vector<int> &heights) {
		auto sz = (int)heights.size();
		if (sz < 3) return 0;
		int l = 0, r = sz-1, left = heights[l], right = heights[r];
		int rc = 0;
		while (l < r) {
			if (left < right) {
				++l;
				if (heights[l] < left) rc += left-heights[l];
				else left = heights[l];
			} else {
				--r;
				if (heights[r] < right) rc += right-heights[r];
				else right = heights[r];
			}
		}
		return rc;
	}
};
posted @ 2015-10-15 01:45  影湛  阅读(110)  评论(0编辑  收藏  举报