zoukankan      html  css  js  c++  java
  • LeetCode OJ 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!


    【题目分析】

    题目给出一个整数序列代表高度图,要求计算下雨后图中的积水量。


    【思路】

    我们只要找到高度图中的凹陷部分,然后把所有凹陷的容积加起来即可。那么如何找到这些凹陷部分呢?

    有这样一个想法:给定高度图两端的高度,那些比这两端都低的部分肯定会形成凹陷,如果是相等则不形成凹陷,如果比当前高度高,则我们要重新确定高度图的两端高度。这个过程如下:

    1. 初始两端最低高度high = 0, 容量capacity = 0;

    2. height[begin] <= high,不形成凹陷,begin++;

    3. height[begin] > high; height[end] > high;high = min(height[begin], height[end]); 因此high = 1;

    此时height[begin] == high,height[end] == high;所以begin++,end--;

    4. height[begin] < high;形成凹陷,capacity += high - height[begin];此时capacity  = 1;begin++;

    5. height[begin] > high; height[end] > high;high = min(height[begin], height[end]); 因此high = 2;

    此时height[begin] == high,height[end] == high;所以begin++,end--;

    6. height[begin] < high;形成凹陷,capacity += high - height[begin];此时capacity  = 2;begin++;

    height[end] < high;形成凹陷,capacity += high - height[begin];此时capacity  = 3;end--;

    7. height[begin] < high;形成凹陷,capacity += high - height[begin];此时capacity  = 5;begin++;

    height[end] = high;不形成凹陷;end--;

    7. height[begin] < high;形成凹陷,capacity += high - height[begin];此时capacity  = 6;begin++;

    8. 返回最大容量6;


    【java代码】

     1 public class Solution {
     2     public int trap(int[] height) {
     3         if(height == null || height.length <= 2) return 0;
     4         
     5         int sum = 0, maxhigh = 0;
     6         int begin = 0, end = height.length-1;
     7         while(begin <= end){
     8             if(height[begin] < maxhigh){
     9                 sum += maxhigh - height[begin++];
    10             }
    11             else if(height[end] < maxhigh){
    12                 sum += maxhigh - height[end--];
    13             }
    14             else{
    15                 maxhigh = Math.min(height[begin], height[end]);
    16                 if(height[begin] <= maxhigh) begin++;
    17                 if(height[end] <= maxhigh) end--;
    18             }
    19         }
    20         return sum;
    21     }
    22 }

  • 相关阅读:
    图片一句话木马简单制作方法
    kali各工具使用介绍
    隐写工具zsteg安装及使用教程
    内网渗透中mimikatz的使用
    kali meterpreter中mimikatz模块获取密码
    一个恐怖份子上传了这张照片到社交网络。里面藏了什么信息?
    攻防世界MISC进阶之签到题
    EMC存储重装系统分区丢失恢复方法
    服务器数据迁移方法
    教您分辨U盘不能识别是哪儿坏了
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5665746.html
Copyright © 2011-2022 走看看