[LeetCode] 42. 接雨水

脑壳铁了,只想到用栈,没什么思路我的妈

题解中用栈的思路是:

class Solution {
    public int trap(int[] height) {
        int sum=0;
        Stack<Integer> stack=new Stack<>();
        int current=0;
        while(current<height.length){
            while(!stack.empty()&&height[current]>height[stack.peek()]){
                int h=height[stack.peek()];
                stack.pop();
                if(stack.empty()){
                    break;
                }
                int distance=current-stack.peek()-1;
                int min=Math.min(height[stack.peek()],height[current]);
                sum=sum+distance*(min-h);
            }
            stack.push(current);
            current++;
        }
        return sum;
    }
}

慢的要死哈

 

 方法二:单独求每一列的值,更慢了。。。。

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

 

 方法三:

动态规划,用一个数组来记录之前得到的值。

class Solution {
    public int trap(int[] height) {
        int sum = 0;
        int[] max_left = new int[height.length];
        int[] max_right = new int[height.length];
    
        for (int i = 1; i < height.length - 1; i++) {
            max_left[i] = Math.max(max_left[i - 1], height[i - 1]);
        }
        for (int i = height.length - 2; i >= 0; i--) {
            max_right[i] = Math.max(max_right[i + 1], height[i + 1]);
        }
        for (int i = 1; i < height.length - 1; i++) {
            int min = Math.min(max_left[i], max_right[i]);
            if (min > height[i]) {
                sum = sum + (min - height[i]);
        }
    }
    return sum;
    }
}

天 这个添加了一个备用数组就快了这么多,牛

 

 还有一个优化动态规划的,待定!!!!

posted @ 2020-04-10 20:33  doyi  阅读(137)  评论(0编辑  收藏  举报