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

代码随想录

相关推荐
小陈phd3 小时前
多模态大模型学习笔记(七)——多模态数据的表征与对齐
人工智能·算法·机器学习
雨泪丶3 小时前
代码随想录算法训练营-Day35
算法
pursuit_csdn3 小时前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
NAGNIP4 小时前
一文搞懂神经元模型是什么!
人工智能·算法
董董灿是个攻城狮4 小时前
AI 视觉连载6:传统 CV 之高斯滤波
算法
散峰而望6 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
Ethan Hunt丶7 小时前
MSVTNet: 基于多尺度视觉Transformer的运动想象EEG分类模型
人工智能·深度学习·算法·transformer·脑机接口
仟濹7 小时前
【算法打卡day10(2026-02-24 周二)复习算法:DFS BFS 并查集】
算法·深度优先·图论·dfs·bfs·广度优先·宽度优先
-海绵东东-7 小时前
哈希表······················
算法·leetcode·散列表