【leetcode】42. Trapping Rain Water

来源:互联网 发布:8通道网络开关 编辑:程序博客网 时间:2024/05/17 01:55

思路:

当前数字左右两边的最大值的最小值减去当前数字的大小即为当前数字所能容纳的水的体积。

总体思想就是扫两遍,然后依次记录对应的最左和最右的最大值。

/** * @author          johnsondu * @problem         Trapping Rain Water * @time            O(n) * @space           O(n) * @url             https://leetcode.com/problems/trapping-rain-water/ * @strategy        traverse 2 times, to get corresponding highest numbei index in left & right * @status          Accepted,   runtime beats 27.60% of cpp submissions. 8ms * @time            20:11 Nov 11th 2015 */class Solution {public:    int trap(vector<int>& height) {        int nums = height.size();        if(nums < 3) return 0;        vector<int> maxL(nums, 0);        vector<int> maxR(nums, 0);                maxL[0] = height[0];        for(int i = 1; i < nums; i ++) {            maxL[i] = maxL[i-1];            if(height[i] > maxL[i])                maxL[i] = height[i];        }                maxR[nums-1] = height[nums-1];        for(int i = nums-2; i >= 0; i --) {            maxR[i] = maxR[i+1];            if(height[i] > maxR[i])                 maxR[i] = height[i];        }                int ans = 0;        for(int i = 1; i < nums-1; i ++) {            ans += min(maxR[i], maxL[i]) - height[i];        }                        return ans;    }};


0 0