Contents

LeetCode42接雨水

Contents

接雨水

public class leetcode42 {
    public int trap(int[] height) {
        int[] temp = new int[height.length];
        temp[0] = 0;
        temp[height.length - 1] = 0;
        for (int i = 1; i < height.length - 1; i++) {
            temp[i] = Math.min(maxTargetOfArray(0, i-1, height), maxTargetOfArray(i + 1, height.length - 1, height)) - height[i] > 0 ? Math.min(maxTargetOfArray(0, i-1, height), maxTargetOfArray(i + 1, height.length - 1, height)) - height[i] : 0;
        }

        int result = 0;
        for (int num : temp){
            result += num;
        }
        return  result;
    }
    public int maxTargetOfArray(int a, int b,int[] c){
        int max = 0;
        for (int temp = a; temp<=b; temp++) {
            if(c[temp] > max){
                max = c[temp];
            }
        }
        return max;
    }
    public static void main(String[] args) {
        int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
        leetcode42 leetcode42 = new leetcode42();
        System.out.println(leetcode42.trap(height));
    }
}

超时时间复杂度O(n^2),正常O(n)

下面是正解

import java.util.Arrays;

public class leetcode42 {
    public int trap(int[] height) {
        int[] temp = new int[height.length];
        temp[0] = 0;
        int max = height[0];
        for (int i = 1; i < height.length; i++) {
            if(height[i-1] > max)
                max = height[i-1];
            temp[i] = max;
        }

        int[] temp1 = new int[height.length];
        temp1[height.length-1] = 0;
        int max1 = height[height.length-1];
        for (int i = height.length-2; i >= 0; i--) {
            if(height[i+1] > max1)
                max1 = height[i+1];
            temp1[i] = max1;
        }

        int target = 0;
        int[] result = new int[height.length];
        for (int i = 0; i < height.length; i++) {
            int min = Math.min(temp[i], temp1[i]);
            if(min > height[i])
                target = min - height[i];
            else
                target = 0;
            result[i] = target;
        }

        for (int nums : result){
            target += nums;
        }

        return target;
    }

    public static void main(String[] args) {
        int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
        leetcode42 leetcode42 = new leetcode42();
        System.out.println(leetcode42.trap(height));
    }
}