Trapping Rain Water

來源:互聯網
上載者:User

標籤:eth   width   height   generate   sys   bsp   todo   cap   info   

描述
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

分析
對於每個柱子,找到其左右兩邊最高的柱子,該柱子能容納的面積就是 min(max_left,
max_right) - height。所以

1. 從左往右掃描一遍,對於每個柱子,求取左邊最大值;
2. 從右往左掃描一遍,對於每個柱子,求最大右值;
3. 再掃描一遍,把每個柱子的面積並累加。
也可以,
1. 掃描一遍,找到最高的柱子,這個柱子將數組分為兩半;
2. 處理左邊一半;
3. 處理右邊一半。
代碼 

 1 package StacksAndqueues; 2  3 public class TrappingRainWater { 4  5     public static void main(String[] args) { 6         // TODO Auto-generated method stub 7         //從左往右找到最大,再從右至左找到最大,目前最大-目前array[i];找到其中最小的,即為存水量。 8     int[] array= {0,1,0,2,1,0,1,3,2,1,2,1}; 9     System.out.println(trap(array));10     }11 12     public static int trap(int[] array) {13         if (array.length == 0)14             return 0;15         int len = array.length - 1;16         int[] maxl = new int[len + 1];17         int[] maxr = new int[len + 1];18         int cap = 0, total = 0;19         for (int i = len; i >= 0; i--) {20             maxr[i] = cap;21             if (array[i] > cap)22                 cap = array[i];23         }24         cap = 0;25         for (int i = 0; i <= len; i++) {26             maxl[i] = cap;27             if (array[i] > cap)28                 cap = array[i];29         }30         for (int i = 0; i <= len; i++) {31             int c = Math.min(maxl[i], maxr[i]) - array[i];32             if (c > 0)33                 total += c;34         }35         return total;36     }37 }

 

Trapping Rain Water

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.