Trapping Rain Water

来源:互联网 发布:少年包青天3知乎 编辑:程序博客网 时间:2024/05/22 01:43

为什么我的思路总是和别人的不一样呢……

具体想法是,设想这些墙都是排成一队的人,那么总有一个最高的墙,在这个墙左边,每个墙能存的雨水就和他向右看能看到的墙的个数有关,直到某一个比他还高的墙将他视线挡住为止。那么,在这两个比较高的墙之间,就是可以存雨水的部分。最高墙的右侧类似,只不过是需要向左看。

因此,首先找到最高的墙是哪个,然后左右分开处理即可。

class Solution {public:    int trap(int A[], int n) {        int index_max = -1;        int max = INT_MIN;        for (int i = 0; i < n; ++i)            if (A[i] > max) {                index_max = i;                max = A[i];            }        int res = 0;        int i = 1;        int tmp_max = A[0];        while (i < index_max) {            if (A[i] < tmp_max) {                res += tmp_max - A[i];                ++i;            }            else {                tmp_max = A[i];                ++i;            }        }        i = n - 2;        tmp_max = A[n - 1];        while (i > index_max) {            if (A[i] < tmp_max) {                res += tmp_max - A[i];                --i;            }            else {                tmp_max = A[i];                --i;            }        }        return res;    }};

http://oj.leetcode.com/problems/trapping-rain-water/

0 0
原创粉丝点击