Leetcode 42. Trapping Rain Water

Problem:

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.


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!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Solution:

  此题和Leetcode 11非常相似,先回顾一下Leetcode 11,它要求我们找到在两个柱子中间最大的蓄水量,因此我们就从两端开始不断靠近,靠近原则是短的那边靠近,因为只有短的那边变长才有超过当前最大蓄水量的可能性,长的那边靠近必然是蓄水量越来越少。相似的来看看这道题,left和right分别初始化为最左侧和最右侧,也是短的那边向长的那边靠近,不同的是,在找到比短的那边长的边之前需要不断累加蓄水量。算法时间复杂度为O(n)。

Code:

 

 1 class Solution {
 2 public:
 3     int trap(vector<int>& height) {
 4         int result = 0;
 5         int left = 0;
 6         int right = height.size()-1;
 7         while(left < right){
 8             int minimal = min(height[left],height[right]);
 9             if(minimal == height[left]){
10                 left++;
11                 while(height[left] < minimal){
12                     result += (minimal-height[left]);
13                     left++;
14                 }
15             }
16             else{
17                 right--;
18                 while(height[right] < minimal){
19                     result += (minimal-height[right]);
20                     right--;
21                 }
22             }
23         }
24         return result;
25     }
26 };

 

posted on 2019-01-06 17:08  周浩炜  阅读(189)  评论(0编辑  收藏  举报

导航