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. class Solution {
  4. public:
  5. int trap(const vector<int>& A) {
  6. const int n = A.size();
  7. int *left_peak = new int[n]();
  8. int *right_peak = new int[n]();
  9. for (int i = 1; i < n; i++) {
  10. left_peak[i] = max(left_peak[i - 1], A[i - 1]);
  11. }
  12. for (int i = n - 2; i >=0; --i) {
  13. right_peak[i] = max(right_peak[i+1], A[i+1]);
  14. }
  15. int sum = 0;
  16. for (int i = 0; i < n; i++) {
  17. int height = min(left_peak[i], right_peak[i]);
  18. if (height > A[i]) {
  19. sum += height - A[i];
  20. }
  21. }
  22. delete[] left_peak;
  23. delete[] right_peak;
  24. return sum;
  25. }
  26. };

代码2

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

相关题目

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