1. 程式人生 > 其它 >LeetCode Notes_#42_接雨水

LeetCode Notes_#42_接雨水

LeetCode Notes_#42_接雨水

LeetCode

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)