0
点赞
收藏
分享

微信扫一扫

leetcode42. 接雨水(java)

大漠雪关山月 2022-04-20 阅读 64

困难题全靠题解哈哈哈哈哈

用的单调栈 感谢题解

class Solution {
    public int trap(int[] height) {
        int ans = 0;
        if(height.length < 2) return 0;
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < height.length; i++){
            if(stack.isEmpty()){
                stack.push(i);
            }else if(height[i] <= height[stack.peek()]){
                stack.push(i);
            }else{
                while(!stack.isEmpty() && height[i] > height[stack.peek()]){
                    int b = stack.peek();
                    stack.pop();
                    if(!stack.isEmpty()){
                        int h = Math.min(height[stack.peek()], height[i]) - height[b];
                        int w = i - stack.peek() - 1;
                        ans += h * w; 
                    }
                }
                stack.push(i);
            }
        }
        return ans;
    }
}
举报

相关推荐

0 条评论