代码随想录算法训练营第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;
    }
}

代码随想录

相关推荐
成都易yisdong18 小时前
高程异常计算器:一款集成Geoid、重力场与地磁场的专业工具
算法
王老师青少年编程18 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【反悔贪心】:种树
c++·算法·贪心·反悔贪心·csp·信奥赛·种树
南宫萧幕18 小时前
基于 PSO 的 HEV 能量管理策略:从联合仿真建模到排错实战
开发语言·python·算法·matlab·控制
生物信息与育种18 小时前
全基因组重测序及群体遗传与进化分析技术服务指南
人工智能·深度学习·算法·数据分析·r语言
AI人工智能+电脑小能手18 小时前
【大白话说Java面试题】【Java基础篇】第23题:ConcurrentHashMap的底层原理是什么
java·开发语言·算法·哈希算法·散列表·hash
葳_人生_蕤18 小时前
hot100——回溯和DFS、BFS
算法·深度优先
Eloudy18 小时前
Steane码的稳定子的生成元集计算过程
算法
MegaDataFlowers18 小时前
快速算法验证流水线
算法
Aaron158818 小时前
27DR/47DR/67DR技术对比及应用分析
人工智能·算法·fpga开发·硬件架构·硬件工程·信息与通信·基带工程
alphaTao19 小时前
LeetCode 每日一题 2026/4/27-2026/5/3
算法·leetcode