[Leetcode] Trapping Rain Water

Trapping Rain Water 题解

题目来源:https://leetcode.com/problems/trapping-rain-water/description/


Description

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.

For example,

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

graph

Solution

class Solution {
public:
    int trap(vector<int> &height) {
        if (height.empty()) {  // 注意边界条件判断
            return 0;
        }

        int left = 0, right = height.size() - 1, res = 0;
        int leftTop = height[left], rightTop = height[right];
        while (left < right) {
            if (height[left] < height[right]) {
                ++left;
                if (height[left] > leftTop) {
                    leftTop = height[left];
                } else {
                    res += (leftTop - height[left]);
                }
            } else {
                --right;
                if (height[right] > rightTop) {
                    rightTop = height[right];
                } else {
                    res += (rightTop - height[right]);
                }
            }
        }

        return res;
    }
};

解题描述

这道题题意是,给出一个数组代表地面上的高地高度,求这一片高地里面所有“低洼”的地方下雨之后可以装多少雨水(如题目描述中的示意图所示)。上面给出的解法是标答中最优的解法,拥有O(n)的时间复杂度和常数级别的空间复杂度。主要的想法是使用左右2个游标“夹逼”的办法:

设左右最高高地高度为leftTop = 0,rightTop = 0;

当左右游标不重合:
    比较左右游标上高地的高度:
        若左游标位置上高地较低:
            如果左游标高地高度高于leftTop:
                将leftTop置为左游标高地高度
            反之将两者的高度差加到结果中
            左游标往右移动
        若右游标位置上高地较低,与左游标处理方法同理
posted @ 2018-03-01 17:03  言何午  阅读(122)  评论(0编辑  收藏  举报