LeetCode:42. 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.

                                                 
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

方法1:(暴力算法 brute force)

class Solution {
    public int trap(int[] height) {
        if (height == null || height.length < 3) {
            return 0;
        }
        
    int ans = 0;
    int size = height.length;
    for (int i = 1; i < size - 1; i++) {
        int max_left = 0, max_right = 0;
        for (int j = i; j >= 0; j--) { 
            max_left = Math.max(max_left, height[j]);
        }
        for (int j = i; j < size; j++) { 
            max_right = Math.max(max_right, height[j]);
        }
        ans += Math.min(max_left, max_right) - height[i];
    }
    return ans;    
    }
}

时间复杂度:O(n^2)

空间复杂度:O(1)


方法2:(两个指针的方式)

class Solution {
    public int trap(int[] height) {
        int l=0, r=height.length-1;
        int lmax =0, rmax=0;
        int ans=0;
        while(l<r){
            if(height[l] < height[r]) {
                if(height[l] > lmax){
                    lmax = height[l];
                }else{
                    ans+=lmax-height[l];
                }
                l++;
            } else {
                if(height[r] > rmax){
                    rmax = height[r];
                }else{
                    ans+= rmax-height[r];
                }
                r--;
            }
        }
        return ans;
    }
}

时间复杂度:O(n)

空间复杂度:O(1)


源码github地址:https://github.com/zhangyu345293721/leetcode

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/85164977