代码随想录打卡第六十天

编程入门 行业动态 更新时间:2024-10-09 07:19:56

代码随想录打卡第六<a href=https://www.elefans.com/category/jswz/34/1747679.html style=十天"/>

代码随想录打卡第六十天

739. 每日温度

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

题目链接: 739. 每日温度
解题思路:
维持一个递减的单调栈,一旦,没有递减 进行出栈 当前元素大于栈顶元素则说明栈顶元素找到下一个更高温度,记录结果并出栈
代码:

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
解题思路及代码如下:

        //暴力法//遍历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;}
}

更多推荐

代码随想录打卡第六十天

本文发布于:2023-11-16 21:34:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633555.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:十天   代码   随想录

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!