leetcode系列(57)Trapping Rain Water

来源:互联网 发布:三星s8打不开淘宝 编辑:程序博客网 时间:2024/05/31 06:21

Given n non-negativeintegers representing an elevation map where the width of each bar is 1, computehow much water it is able to trap after raining.

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

解答:这个题目可以解读为求每个柱子可以"顶"多少水(height),分析可发现每个柱子上能"顶"的水与它左边和右边最高柱子的最小的那个高度有关(最大值中求最小,是不是有点二份答案的味道),咋一看在遍历每个柱子的时候,需要左右各自搜索最大高度,时间复杂度O(n^2),但是其实不必的,首先用一个数组存储每个柱子的max_right_height,可以从右往左遍历并更新每个柱子的max_right_height,而max_left_height只需在从左到右遍历一边求每个柱子能顶多少水的时候一边更新,这里也给出了一些其它的解法,有点意思可以看下。

class Solution {public:    int trap(vector<int>& height) {        // the trap water of i is min(max height(0:i), max height(i+1:n)) - height[i]        // use a vector to record max right height from the end to the first        // traverse from left to right and update the current max left height of i        // so traverse twic right to left and left to right        vector<int> max_right(height.size(), 0);        int ret = 0;        int cur_max = 0;        for (int i = static_cast<int>(height.size() - 1); i >= 0; --i) {            max_right[i] = cur_max;            cur_max = std::max(cur_max, height[i]);        }        cur_max = 0;        for (size_t i = 0; i < height.size(); ++i) {            int cur_height = std::min(cur_max, max_right[i]);            if (cur_height > height[i]) {                ret += cur_height - height[i];            }            cur_max = std::max(cur_max, height[i]);        }        return ret;    }};


0 0
原创粉丝点击