zoukankan      html  css  js  c++  java
  • [LeetCode] #42 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.

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

    The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

    本题利用短板效应,从两端开始,依此寻找最短边所能存储到的最多的水,然后更新最短边。例如left height=1,right height=2,然后从左侧寻找,height=2,left height=2,water+=1。时间:8ms。代码如下:

    class Solution {
    public:
        int trap(vector<int>& height) {
            if (height.empty() || height.size() == 1)
                return 0;
            int left = 0, right = height.size() - 1;
            int water = 0;
            while (left < right){
                if (height[left] < height[right]){
                    int i = left + 1;
                    while (i < right && height[i] < height[left])
                        water += height[left] - height[i++];
                    left = i;
                }
                else{
                    int i = right - 1;
                    while (i > left && height[i] < height[right])
                        water+=height[right] - height[i--];
                    right = i;
                }
            }
            return water;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    Python中的类(上)
    Django REST Framework API Guide 07
    Django REST Framework API Guide 06
    Django REST Framework API Guide 05
    Django REST Framework API Guide 04
    Django REST Framework API Guide 03
    Django REST Framework API Guide 02
    Django REST Framework API Guide 01
    Django 详解 信号Signal
    Django 详解 中间件Middleware
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4583714.html
Copyright © 2011-2022 走看看