zoukankan      html  css  js  c++  java
  • LeetCode Notes_#42_接雨水

    LeetCode Notes_#42_接雨水

    Contents

    题目


    解法

    记住一个公式,
    当前位置雨水高度 = min(当前位置左边最高高度,当前位置右边最高高度) - 当前位置高度
    那么其实问题就归结为,先计算出每个位置左右两边的最高高度。然后根据这个数据,就可以求出雨水面积。

    class Solution {
        public int trap(int[] height) {
            int n = height.length;
            int[] leftMax = new int[n];
            int[] rightMax = new int[n];
            leftMax[0] = height[0];
            for(int i = 1; i < n; i++){
                leftMax[i] = Math.max(height[i], leftMax[i - 1]);
            }
            rightMax[n - 1] = height[n - 1];
            for(int i = n - 2; i >= 0; i--){
                rightMax[i] = Math.max(height[i], rightMax[i + 1]);
            }
            int area = 0;
            for(int i = 1; i < n - 1; i++){
                area += Math.min(leftMax[i], rightMax[i]) - height[i];
            }
            return area;
        }
    }

    时间复杂度:O(n)
    空间复杂度:O(n)

  • 相关阅读:
    Storm 中drpc调用
    yarn下资源配置
    java 中 Stringbuff append源代码浅析
    总结的MR中连接操作
    hive中使用rcfile
    MapFile
    HDFS副本存放读取
    zoj 1967 Fiber Network/poj 2570
    zoj 2027 Travelling Fee
    poj 1742 Coins
  • 原文地址:https://www.cnblogs.com/Howfars/p/15679622.html
Copyright © 2011-2022 走看看