代码随想录打卡第六十天|● 739. 每日温度 ● 496.下一个更大元素 I

739. 每日温度

题目: 给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

题目链接: 739. 每日温度
解题思路:

维持一个递减的单调栈,一旦,没有递减 进行出栈 当前元素大于栈顶元素则说明栈顶元素找到下一个更高温度,记录结果并出栈

代码:

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

496.下一个更大元素 I

题目: nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。

题目链接: 496. 下一个更大元素 I
解题思路及代码如下:

java 复制代码
        //暴力法
        //遍历nums1 在nums2中找nums1下一个更大
        //单调栈法 使用map存储nums1 对nums2使用单调栈发 将值赋给nums1的对应位置
class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Stack<Integer> temp = new Stack<>();
        int[] res = new int[nums1.length];
        Arrays.fill(res,-1);
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0 ; i< nums1.length ; i++){
            hashMap.put(nums1[i],i);
        }
        temp.add(0);
        for (int i = 1; i < nums2.length; i++) {
            if (nums2[i] <= nums2[temp.peek()]) {
                temp.add(i);
            } else {
                while (!temp.isEmpty() && nums2[temp.peek()] < nums2[i]) {
                    if (hashMap.containsKey(nums2[temp.peek()])){
                        Integer index = hashMap.get(nums2[temp.peek()]);
                        res[index] = nums2[i];
                    }
                    temp.pop();
                }
                temp.add(i);
            }
        }

        return res;
    }
}
相关推荐
是小Y啦10 分钟前
leetcode 106.从中序与后续遍历序列构造二叉树
数据结构·算法·leetcode
万河归海42828 分钟前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio
秋夫人2 小时前
B+树(B+TREE)索引
数据结构·算法
代码雕刻家2 小时前
数据结构-3.1.栈的基本概念
c语言·开发语言·数据结构
AlexMercer10123 小时前
【C++】二、数据类型 (同C)
c语言·开发语言·数据结构·c++·笔记·算法
^^为欢几何^^5 小时前
lodash中_.difference如何过滤数组
javascript·数据结构·算法
ahauedu6 小时前
案例分析-Stream List 中取出值最大的前 5 个和最小的 5 个值
数据结构·list
X同学的开始7 小时前
数据结构之二叉树遍历
数据结构
AIAdvocate11 小时前
Pandas_数据结构详解
数据结构·python·pandas
jiao0000111 小时前
数据结构——队列
c语言·数据结构·算法