Day 52 || 739. 每日温度 、 496.下一个更大元素 I 、503.下一个更大元素II

739. 每日温度

题目链接: 力扣题目链接

**思路:**需要使用到单调栈,单调栈记录放入当前值所在数组的位置,只要当前数小于栈顶就放入,要是大于栈顶就弹出当记录的数组危及减去当前for循环的位置。

※要是求左侧或者右侧最大值栈就是从栈顶往栈底依次递增,相反左侧或者右侧最小值就是栈顶往栈底递减。

复制代码
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        int[] res = new int[temperatures.length];
        for(int i=1;i<temperatures.length;i++){
            if(temperatures[i]<=temperatures[stack.peek()]){
                stack.push(i);
            }else{
                while(!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]){
                    int prevIndex = stack.pop();
                    res[prevIndex] = i- prevIndex;
                }
                stack.push(i);
            }
        }
        return res;
    }
}

496.下一个更大元素 I

题目链接: 力扣题目链接

思路: 和"739. 每日温度"差不多,可以创建一个HashMap保存nums2的结果,便于nums1在其中快速找到结果。

496.下一个更大元素 I

题目链接: 力扣题目链接

**思路:**题目关键是如何将数组循环起来,可以for循环的长度乘以二,然后利用 i%nums.length来取余用来获得当前值,其他的就都相同,结果就是新的数组从零开始取原数组的长度的值。

复制代码
import java.util.Stack;
import java.util.Arrays;

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        int[] res = new int[nums.length];
        Arrays.fill(res, -1);  // 初始化结果数组为 -1
        
        // 遍历 nums 数组两遍来模拟循环数组的效果
        for (int i = 0; i < nums.length * 2; i++) {
            int currentIndex = i % nums.length;  // 当前索引,使用模运算实现循环
            // 当栈不为空并且栈顶元素对应的值小于当前元素
            while (!stack.isEmpty() && nums[stack.peek()] < nums[currentIndex]) {
                int prevIndex = stack.pop();  // 弹出栈顶元素的索引
                res[prevIndex] = nums[currentIndex];  // 更新结果数组
            }
            // 只在第一次遍历时将当前索引压入栈
            if (i < nums.length) {
                stack.push(currentIndex);  // 将当前元素的索引压入栈
            }
        }
        
        return res;
    }
}

时间:2h

相关推荐
孤飞2 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
技术专家3 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
csdn_aspnet3 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp3 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium5 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5636 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮6 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11016 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先
会编程的土豆7 小时前
01背包与完全背包详解
开发语言·数据结构·c++·算法
汀、人工智能7 小时前
[特殊字符] 第86课:最大正方形
数据结构·算法·数据库架构·图论·bfs·最大正方形