42. 接雨水

265 阅读1分钟

感觉还是比较特殊的题型,单调栈的解法,定义一个Stack类型的低洼处,遇到积雨就需要进行一个入栈,在接下来的判断中,需要判断积雨地整体是否还是一个低洼状态(积雨地是否还能组成水坑,判断方式是低洼处中是否还存在元素),其次需要判断当前是否能够组成一个低洼处(stack.peek()取出值,此处使用if(stack.isEmpty())进行判断,确定仍然存在积雨处

import java.util.Stack;

/**
 * DropWater
 *
 * @author Scottish
 * @date 2021/5/21
 */
public class DropWater {

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


    public static int trap(int[] height) {
        if(height.length == 0) {
            return 0;
        }
        int area = 0;
        Stack<Integer> lowIsland = new Stack<>();
        for(int i = 0 ; i < height.length ; i++) {
            while(!lowIsland.isEmpty() && height[i] > height[lowIsland.peek()]) {
                int cur = lowIsland.pop();
                if(lowIsland.isEmpty()) {
                    break;
                }
                int left = lowIsland.peek();
                int h = Math.min(height[i],height[left]) - height[cur];
                int w = i - left - 1;
                System.out.println("i: " + i + "left: " + left);
                area = area + h * w;
            }
            lowIsland.push(i);
        }
        return area;
    }
}