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

代码随想录

相关推荐
写代码的小球1 小时前
求模运算符c
算法
大千AI助手4 小时前
DTW模版匹配:弹性对齐的时间序列相似度度量算法
人工智能·算法·机器学习·数据挖掘·模版匹配·dtw模版匹配
YuTaoShao6 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
生态遥感监测笔记6 小时前
GEE利用已有土地利用数据选取样本点并进行分类
人工智能·算法·机器学习·分类·数据挖掘
Tony沈哲7 小时前
macOS 上为 Compose Desktop 构建跨架构图像处理 dylib:OpenCV + libraw + libheif 实践指南
opencv·算法
刘海东刘海东7 小时前
结构型智能科技的关键可行性——信息型智能向结构型智能的转变(修改提纲)
人工智能·算法·机器学习
pumpkin845148 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust
挺菜的8 小时前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法
mit6.8248 小时前
7.6 优先队列| dijkstra | hash | rust
算法