LintCode 363. 接雨水 题解
描述
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.
样例
如上图所示,海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1]
, 返回 6
.
挑战
O(n) 时间, O(1) 空间
O(n) 时间, O(n) 空间也可以接受
思路:搞清楚雨水能积累下来的条件就差不多知道该怎么做了,要注意对整个数组中最大高度的关注。
我的做法是从两边往中间逼近,最后在整个数组的最高点汇合,只有中间比两边高度低的时候才计入雨水,因为保证了最高点最后取到所以能保持两边往中间累计的雨水。
时间复杂度O(n),空间复杂度O(1)。
C++ AC代码(278ms):
1 class Solution { 2 public: 3 /** 4 * @param heights: a list of integers 5 * @return: a integer 6 */ 7 int trapRainWater(vector<int> &heights) { 8 // write your code here 9 int size = heights.size(); 10 if(size <= 2) return 0; 11 int left_max = 0;//两侧最高挡板 12 int right_max = 0; 13 int left_cur = 0; 14 int right_cur = size - 1; 15 int res = 0; 16 while(left_cur != right_cur){ 17 if(heights[left_cur] <= heights[right_cur]){//保证较小的一边向中间靠近,最后汇合于最大值 18 if(heights[left_cur]>left_max){//判断是否累计雨水 19 left_max = heights[left_cur++]; 20 }else{ 21 res += (left_max-heights[left_cur++]); 22 } 23 }else{ 24 if(heights[right_cur]>right_max){ 25 right_max = heights[right_cur--]; 26 }else{ 27 res += (right_max-heights[right_cur--]); 28 } 29 } 30 } 31 return res; 32 } 33 };
Know More ,Do More.