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.

Trapping Rain Water

Figure: Trapping Rain Water

分析

对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是min(max_left, max_right) - height。所以,

  • 从左往右扫描一遍,对于每个柱子,求取左边最大值;
  • 从右往左扫描一遍,对于每个柱子,求最大右值;
  • 再扫描一遍,把每个柱子的面积并累加。
    也可以,

  • 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;

  • 处理左边一半;
  • 处理右边一半。

    代码1

  1. // Trapping Rain Water
  2. // 思路1,时间复杂度O(n),空间复杂度O(n)
  3. public class Solution {
  4. public int trap(int[] A) {
  5. final int n = A.length;
  6. int[] left_peak = new int[n];
  7. int[] right_peak = new int[n];
  8. for (int i = 1; i < n; i++) {
  9. left_peak[i] = Math.max(left_peak[i-1], A[i-1]);
  10. }
  11. for (int i = n - 2; i >=0; --i) {
  12. right_peak[i] = Math.max(right_peak[i+1], A[i+1]);
  13. }
  14. int sum = 0;
  15. for (int i = 0; i < n; i++) {
  16. int height = Math.min(left_peak[i], right_peak[i]);
  17. if (height > A[i]) {
  18. sum += height - A[i];
  19. }
  20. }
  21. return sum;
  22. }
  23. };

代码2

  1. // Trapping Rain Water
  2. // 思路2,时间复杂度O(n),空间复杂度O(1)
  3. public class Solution {
  4. public int trap(int[] A) {
  5. final int n = A.length;
  6. int peak_index = 0; // 最高的柱子,将数组分为两半
  7. for (int i = 0; i < n; i++)
  8. if (A[i] > A[peak_index]) peak_index = i;
  9. int water = 0;
  10. for (int i = 0, left_peak = 0; i < peak_index; i++) {
  11. if (A[i] > left_peak) left_peak = A[i];
  12. else water += left_peak - A[i];
  13. }
  14. for (int i = n - 1, right_peak = 0; i > peak_index; i--) {
  15. if (A[i] > right_peak) right_peak = A[i];
  16. else water += right_peak - A[i];
  17. }
  18. return water;
  19. }
  20. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/array/trapping-rain-water.html