代码随想录算法训练营第49天

42. 接雨水

接雨水这道题目是 面试中特别高频的一道题,也是单调栈 应用的题目,大家好好做做。

建议是掌握 双指针 和单调栈,因为在面试中 写出单调栈可能 有点难度,但双指针思路更直接一些。

在时间紧张的情况有,能写出双指针法也是不错的,然后可以和面试官在慢慢讨论如何优化。

代码随想录

java 复制代码
class Solution {
    public int trap(int[] height) {
        int total = 0;
        for (int index = 0; index < height.length; index++) {
            if (index == 0 || index == height.length - 1) continue;

            int rightMax = height[index]; 
            int leftMax = height[index]; 
            for (int right = index + 1; right < height.length; right++) {
                rightMax = Math.max(rightMax, height[right]);
            }
            for (int left = index - 1; left >= 0; left--) {
                leftMax = Math.max(leftMax, height[left]);
            }
            int waterHeight = Math.min(leftMax, rightMax) - height[index];
            if (waterHeight > 0) total += waterHeight;
        }
        return total;
    }
}
  1. 柱状图中最大的矩形

有了之前单调栈的铺垫,这道题目就不难了。

java 复制代码
class Solution {
    public int largestRectangleArea(int[] heights) {
        int[] extendedHeights = new int[heights.length + 2];
        System.arraycopy(heights, 0, extendedHeights, 1, heights.length);
        extendedHeights[0] = 0;
        extendedHeights[heights.length + 1] = 0;

        Stack<Integer> stack = new Stack<>();
        stack.push(0);

        int maxArea = 0;
        for (int i = 1; i < extendedHeights.length; i++) {
            while (!stack.isEmpty() && extendedHeights[i] < extendedHeights[stack.peek()]) {
                int topIndex = stack.pop();
                int width = i - stack.isEmpty() ? 0 : i - stack.peek() - 1;
                int height = extendedHeights[topIndex];
                maxArea = Math.max(maxArea, width * height);
            }
            stack.push(i);
        }
        return maxArea;
    }
}

代码随想录

相关推荐
天上路人21 分钟前
AI神经网络降噪算法在语音通话产品中的应用优势与前景分析
深度学习·神经网络·算法·硬件架构·音视频·实时音视频
好吃的肘子25 分钟前
MongoDB 应用实战
大数据·开发语言·数据库·算法·mongodb·全文检索
汉克老师40 分钟前
GESP2025年3月认证C++二级( 第三部分编程题(1)等差矩阵)
c++·算法·矩阵·gesp二级·gesp2级
sz66cm1 小时前
算法基础 -- 小根堆构建的两种方式:上浮法与下沉法
数据结构·算法
緈福的街口1 小时前
【leetcode】94. 二叉树的中序遍历
算法·leetcode
小刘要努力呀!1 小时前
嵌入式开发学习(第二阶段 C语言基础)
c语言·学习·算法
野曙2 小时前
快速选择算法:优化大数据中的 Top-K 问题
大数据·数据结构·c++·算法·第k小·第k大
Codeking__3 小时前
”一维前缀和“算法原理及模板
数据结构·算法
休息一下接着来3 小时前
C++ 条件变量与线程通知机制:std::condition_variable
开发语言·c++·算法
Code哈哈笑3 小时前
【机器学习】支持向量回归(SVR)从入门到实战:原理、实现与优化指南
人工智能·算法·机器学习·回归·svm