zoukankan      html  css  js  c++  java
  • 【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;
        }
    };

      其他解法见此处

  • 相关阅读:
    http简记
    socket简介
    iOS代理
    ai作图小技能
    按钮切换
    关于ie8背景图片的平铺
    关于文本省略
    关于html table样式
    阿里巴巴iconfont使用方法(超级详细)
    办公电脑安装虚拟机基本就绪
  • 原文地址:https://www.cnblogs.com/Atanisi/p/7066850.html
Copyright © 2011-2022 走看看