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!


    分析
    空间复杂度O(n)
    对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是 min(max_left,max_right) - height。所以
    1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;
    2. 从右往左扫描一遍,对于每个柱子,求最大右值;
    3. 再扫描一遍,把每个柱子的面积并累加。
    1. class Solution {
    2. public:
    3. int trap(vector<int>& height) {
    4. int length=height.size();
    5. int *max_left=new int[length]();
    6. int *max_right=new int[length]();
    7. for(int i=1;i<length;i++){
    8. max_left[i]=max(max_left[i-1],height[i-1]);
    9. max_right[length-i-1]=max(max_right[length-i],height[length-i]);
    10. }
    11. int sum=0;
    12. for (int i=0;i<length;i++){
    13. int h=min(max_left[i],max_right[i]);
    14. if(h>height[i])
    15. sum+=h-height[i];
    16. }
    17. delete[]max_left;
    18. delete[]max_right;
    19. return sum;
    20. }
    21. };

    也可以,该方法空间复杂度O(1)
    1. 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;
    2. 处理左边一半;
    3. 处理右边一半。
     
    1. class Solution {
    2. public:
    3. int trap(vector<int>& height) {
    4. int max = 0; // 最高的柱子,将数组分为两半
    5. int n=height.size();
    6. for (int i = 0; i < n; i++)
    7. if (height[i] > height[max]) max = i;
    8. int water = 0;
    9. for (int i=0,peak=0;i<max;i++){
    10. if(peak<height[i])peak=height[i];
    11. else
    12. water+=peak-height[i];
    13. }
    14. for(int j=n-1,peak=0;j>max;j--){
    15. if(peak<height[j])peak=height[j];
    16. else
    17. water+=peak-height[j];
    18. }
    19. return water;
    20. }
    21. };






  • 相关阅读:
    GDB编辑、搜索源码以及在线帮助
    GDB查看栈信息
    GDB信号处理
    GDB反向调试
    GDB调试多进程程序
    GDB后台调试命令
    GDB non-stop模式
    GDB调试多线程程序
    GDB禁用删除断点
    解决Mac OS下Eclipse、IntelliJ IDEA打开其他窗口默认全屏
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/5284977.html
Copyright © 2011-2022 走看看