Skip to content

Latest commit

 

History

History
48 lines (37 loc) · 1.25 KB

42. Trapping Rain Water.md

File metadata and controls

48 lines (37 loc) · 1.25 KB

42. Trapping Rain Water

https://leetcode.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 is able to trap after raining.

img 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!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

代码

class Solution {
    public int trap(int[] height) {
        if (height == null || height.length < 3) {
            return 0;
        }
        int vol = 0;
        int left = 0, right = height.length - 1;
        int lmax = height[left];
        int rmax = height[right];
        
        while (left < right) {
            lmax = Math.max(lmax, height[left]);
            rmax = Math.max(rmax, height[right]);
            
            if (lmax <= rmax) {
                vol += lmax - height[left];
                left++;
            }
            
            else {
                vol += rmax - height[right];
                right--;
            }
        }
        return vol;
    }
}