【Lintcode】363.Trapping Rain Water

题目:

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.

Trapping Rain Water

Example

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

题解:

  读题可知,区间[a,b]内容积由边缘最小值决定,Two pointer思想,遍历整个数组。每一次都是寻找两端最小值,然后开始遍历,遇到更大值后替换端值(不能盛水了)。

Solution 1 () (from here 九章算法)

class Solution {
public:
    int trapRainWater(vector<int> &heights) {
        int left = 0, right = heights.size() - 1;
        int res = 0;
        if (left >= right) {
            return res;
        }
        int lheight = heights[left];
        int rheight = heights[right];
        while (left < right) {
            if (lheight < rheight) {
                ++left;
                if (lheight > heights[left]) {
                    res += lheight - heights[left];
                } else {
                    lheight = heights[left];
                }
            } else {
                --right;
                if (rheight > heights[right]) {
                    res += rheight - heights[right];
                } else {
                    rheight = heights[right];
                }
            }
        }
        return res;
    }
};

  其他解法见此处

posted @ 2017-06-22 19:35  Vincent丶丶  阅读(206)  评论(0编辑  收藏  举报