首页 > 技术文章 > Leetcode 42. Trapping Rain Water

lantx 2017-02-27 15:01 原文

题目:

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.


思路:


代码:

class Solution {
public:
    int trap(vector<int>& height) {
  		int length = height.size();
  		int secHeight = 0, left = 0, right = length -1, ans = 0;
  		while(left < right) {
  			if (height[left] < height[right])
  			{
  				secHeight = max(secHeight, height[left]);
  				ans += secHeight - height[left];
  				left ++;
  			}
  			else 
  			{
  				secHeight = max(secHeight, height[right]);
  				ans += secHeight - height[right];
  				right --;
  			}
  		}
  		return ans;
    }
};


 

推荐阅读