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

代码随想录

相关推荐
bkspiderx3 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐4 小时前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸5 小时前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试
一只懒洋洋5 小时前
K-meas 聚类、KNN算法、决策树、随机森林
算法·决策树·聚类
方案开发PCBA抄板芯片解密6 小时前
什么是算法:高效解决问题的逻辑框架
算法
songx_997 小时前
leetcode9(跳跃游戏)
数据结构·算法·游戏
小白狮ww7 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥7 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
kk”8 小时前
C语言快速排序
数据结构·算法·排序算法
纪元A梦8 小时前
贪心算法应用:基因编辑靶点选择问题详解
算法·贪心算法