1. 程式人生 > 其它 >LeetCode T42 Trapping Rain Water

LeetCode T42 Trapping Rain Water

技術標籤:LeetCode300-javaleetcode

文章目錄

題目地址

https://leetcode-cn.com/problems/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 can trap after raining.

Example 1:

在這裡插入圖片描述

Input: height = [0,1,0,2,1,0,1,3,2
,1,2,1] Output: 6 Explanation: The above elevation map (black section) 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.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

  • n == height.length
  • 0 <= n <= 3 * 10^4
  • 0 <= height[i] <= 10^5

思路

對每個柱子上的積水,由其左右兩邊最高的柱子中較矮的柱子決定,因此可以計算每個柱子左右最高的柱子,然後計算其中矮的柱子和當前柱子的差。

題解

class Solution {
    public int trap(int[] height) {
        int res=0,i,j;
        int len = height.length;
        int[] left = new int[len];
        int[] right = new int[len];

        int lmax=0;
        for(i=0;i< height.
length;++i){ left[i]=lmax; lmax = Math.max(lmax,height[i]); } int rmax = 0; for(j= height.length-1;j>=0;--j){ right[j]=rmax; rmax = Math.max(rmax,height[j]); } for(i=0;i<len;i++){ int h = Math.min(left[i],right[i]); if(h>height[i]) res+= h - height[i]; } return res; } }