zoukankan      html  css  js  c++  java
  • 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 public class Solution {
     2     public int trap(int[] A) {
     3         if(A == null || A.length < 3) return 0;
     4         int start = 0, end = A.length - 1;
     5         while(A[start] == 0){
     6             start ++;
     7         }
     8         while(A[end] == 0){
     9             end --;
    10         }
    11         int left = start;
    12         int sum = 0;
    13         for(int i = start + 1; i <= end; i ++){
    14             if(A[i] >= A[left]){
    15                 for(int j = left + 1; j < i; j ++){
    16                     sum += A[left] - A[j];
    17                 }
    18                 left = i;
    19             }
    20         }
    21         int right = end;
    22         for(int i = end - 1; i >= start; i --){
    23             if(A[i] > A[right]){
    24                 for(int j = i + 1; j < right; j ++){
    25                     sum += A[right] - A[j];
    26                 }
    27                 right = i;
    28             }
    29         }
    30         return sum;
    31     }
    32 }

    第三遍:

     1 public class Solution {
     2     public int trap(int[] A) {
     3         if(A == null || A.length < 3) return 0;
     4         int sum = 0;
     5         int start = 0, end = A.length - 1;
     6         while(start < A.length && A[start] == 0) start ++;
     7         while(end > -1 && A[end] == 0) end --;
     8         int per = start, cur = start + 1;
     9         for(; cur <= end; cur ++){
    10             if(A[cur] >= A[per]){
    11                 for(int i = per + 1; i < cur; i ++)
    12                     sum += A[per] - A[i];
    13                 per = cur;
    14             }
    15         }
    16         per = end; cur = end - 1;
    17         for(; cur >= start; cur --){
    18             if(A[cur] > A[per]){
    19                 for(int i = cur + 1; i < per; i ++)
    20                     sum += A[per] - A[i];
    21                 per = cur;
    22             }
    23         }
    24         return sum;
    25     }
    26 }
  • 相关阅读:
    基于arm开发板四个按键控制四个灯亮
    汇编语言实现led灯的跑马灯
    cpsr当前程序状态寄存器
    ewp开发
    erlang学习 d1
    java基础之封装继承
    java面试常见问题
    crm项目复盘
    ssm整合-动态项目-day13
    ssm整合spring,springmvc,mybatis-day12
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3913974.html
Copyright © 2011-2022 走看看