道阻且长,行则将至,走慢一点没关系,不停下就好了.|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2023-12-24 15:46阅读: 5评论: 0推荐: 0

[LeetCode Hot 100] LeetCode42. 接雨水

题目描述

思路一:单调栈

柱子的高度递减的时候是装不了水的,当碰到第一个比之前高的柱子才可以装水。
此时计算栈顶索引能装的水:

  • 宽:i - left - 1(这个left为栈顶元素pop之后的peek值)
  • 高:min(height[left], height[i]) - height[top]
  • 该题维护的是一个单调递减栈


方法一:对应思路一

class Solution {
    public int trap(int[] height) {
        if (height == null || height.length <= 2) return 0;

        // 这里维护的是一个单调递减栈
        Deque<Integer> stack = new ArrayDeque<>();
        int res = 0;

        for (int i = 0; i < height.length; i ++) {
            while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                int top = stack.pop();
                // 这行代码正好能解决示例1中索引0为0的情况
                if (stack.isEmpty()) break;
                int h = Math.min(height[i], height[stack.peek()]) - height[top];
                int w = i - stack.peek() - 1;
                res += h * w;   
            }
            stack.push(i);
        }
        return res;
    }
}

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/17924452.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(5)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.