zoukankan      html  css  js  c++  java
  • leetcode栈--4、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], return6.

    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!

    解题思路:采用dp的思想,定义一个数组,
    1)先从左向右遍历一遍,针对每一个点,求出它左侧最大点,记录在数组中,如图记录结果为 001122223333
    2)再从右向左遍历,针对每一个点,求出其右侧的最大值(左右侧最小值记录在数组中,短板原理),记录结果为  012222221100(B[11]-B[0])
    3)针对每一个点,如果B[i]>A[i]则说明该点可存水(B[i]-A[i])*1
    则求出area
     1 class Solution {
     2 public:
     3     int trap(int A[], int n) {
     4         if(A == NULL || n<=0)
     5             return 0;
     6         int area = 0;
     7         int B[n];
     8         int maxVal = 0;
     9         //从左向右遍历,记录每个点左侧的最大值
    10         for(int i=0;i<n;i++)
    11         {
    12             B[i] = maxVal;
    13             maxVal = max(maxVal,A[i]);
    14         }
    15         maxVal = 0;//重置
    16         //从右向左遍历,找每个点右侧的最大值
    17         for(int i=n-1;i>=0;i--)
    18         {
    19             //短板原理,取左右最大值中最小的
    20             B[i] = min(maxVal,B[i]);
    21             maxVal = max(maxVal,A[i]);
    22             if(B[i]>A[i])
    23                 area+=(B[i]-A[i]);
    24         }
    25         return area;
    26     }
    27 };
  • 相关阅读:
    寒假学习记录19
    寒假学习记录18
    寒假学习记录17
    寒假学习记录16
    寒假学习记录15
    寒假学习记录14
    寒假学习记录13
    寒假学习记录12
    寒假学习记录11
    学习进度(10)
  • 原文地址:https://www.cnblogs.com/qqky/p/6953713.html
Copyright © 2011-2022 走看看