zoukankan      html  css  js  c++  java
  • [leetcode]Trapping Rain Water

    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! 

    算法思路:

    短板效应,蓄水量与桶的短板相关。求出height数组中的最长板,然后从两端向长板迭代,遇到更短的则求出蓄水量,遇到较长的,则更新边缘。

    代码如下:

     1 public class Solution {
     2     public int trap(int[] height) {
     3         if(height == null || height.length < 3) return 0;
     4         int max = 0;
     5         for(int i = 0; i < height.length;i++){
     6             if(height[i] > height[max]) max = i;
     7         }
     8         int high = 0,res = 0;
     9         for(int i = 0; i < max; i++){
    10             if(height[i] < height[high]){
    11                 res += height[high] - height[i];
    12             }else if(height[i] > height[high]){
    13                 high = i;
    14             }
    15         }
    16         high = height.length - 1;
    17         for(int i = height.length - 1; i > max; i--){
    18             if(height[i] < height[high]){
    19                 res += height[high] - height[i];
    20             }else if(height[i] > height[high]){
    21                 high = i;
    22             }
    23         }
    24         return res;
    25     }
    26 }

    具体算法分析可以参考这里

  • 相关阅读:
    POJ 3321:Apple Tree + HDU 3887:Counting Offspring(DFS序+树状数组)
    BZOJ 1026:windy数(数位DP)
    POJ 3087 Shuffle'm Up
    POJ 1835 宇航员
    差分约束系统
    POJ
    2016 百度之星初赛 Gym Class(优先队列+拓扑排序)
    HDU 4786 Fibonacci Tree
    Codeforces 691D Swaps in Permutation
    FZU 2195 检查站点
  • 原文地址:https://www.cnblogs.com/huntfor/p/3898901.html
Copyright © 2011-2022 走看看