【算法二十二】 739. 每日温度 42.接雨水

739. 每日温度

单调栈:

java 复制代码
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        Deque<Integer> stack = new ArrayDeque<>();
        int[] ans = new int[n];
        for(int i = 0;i<n;i++){
            while(!stack.isEmpty() && temperatures[i]>temperatures[stack.peek()]){
                int j = stack.pop();
                
            }
        }
    }
}

时间复杂度:O(N)

空间复杂度:O(N)

核心:

遇到"找右边第一个比我大的数"、"找左边第一个比我小的数"

处理"凹"或"凸"的形状: 比如接雨水(找凹槽)或者最大矩形面积(找左右边界)

计算"跨度"或"贡献": 某个数在什么范围内是最大的?(比如:子数组最小值之和)

42. 接雨水

双指针:

java 复制代码
class Solution {
    public int trap(int[] height) {
        int ans = 0;
        int left = 0;
        int right = height.length - 1;
        int preMax = 0;
        int behMax = 0;
        while(left < right){
            //计算高度包含本高度的原因是,不需要写 if-else 去判断当前柱子是否比最大高度矮
            //矮的可以存水,高的不能存水
            //代码通过一次减法自动兼容了存水还是不能存水的逻辑
            preMax = Math.max(preMax,height[left]);
            behMax = Math.max(behMax,height[right]);
            if(preMax < behMax){
                ans += preMax - height[left];
                left++;
            }
            else{
                ans += behMax - height[right];
                right--;
            }
        }
        return ans;
    }
}

时间复杂度:O(N)

空间复杂度:O(1)

核心:Math.min(preMax,behMax) - height[i]

单调栈:

java 复制代码
class Solution {
    public int trap(int[] height) {
        int ans = 0;
        Deque<Integer> stack = new ArrayDeque<>();
        for(int i = 0;i<height.length;i++){
            while(!stack.isEmpty() && height[stack.peek()]<height[i]){
                int bottom = height[stack.pop()];
                if(stack.isEmpty()){
                    break;
                }
                int left = stack.peek();
                int h = Math.min(height[left],height[i])-bottom;
                ans += h*(i-left-1);
            }
            stack.push(i);
        }
        return ans;
    }
}

时间复杂度:O(N)

空间复杂度:O(N)

相关推荐
一轮弯弯的明月1 小时前
竞赛刷题-建造最大岛屿-Java版
java·算法·深度优先·图搜索算法·学习心得
黑眼圈子1 小时前
牛客刷题记录1
算法
祁同伟.1 小时前
【C++】哈希的应用
开发语言·数据结构·c++·算法·容器·stl·哈希算法
点云SLAM1 小时前
Tracy Profiler 是目前 C++ 多线程程序实时性能分析工具
开发语言·c++·算法·slam·算法性能分析·win环境性能分析·实时性能分析工具
We་ct1 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·leetcode·typescript·深度优先·深度优先遍历
吃着火锅x唱着歌2 小时前
LeetCode 447.回旋镖的数量
算法·leetcode·职场和发展
我能坚持多久2 小时前
【初阶数据结构08】——深入理解树与堆
数据结构·算法
Trouvaille ~2 小时前
【贪心算法】专题(一):从局部到全局,数学证明下的最优决策
c++·算法·leetcode·面试·贪心算法·蓝桥杯·竞赛
iAkuya2 小时前
(leetcode)力扣100 92.最小路径和(动态规划)
算法·leetcode·动态规划