第十章 单调栈part01
● 739. 每日温度
● 496.下一个更大元素 I
详细布置
739. 每日温度
今天正式开始单调栈,这是单调栈一篇扫盲题目,也是经典题。
大家可以读题,思考暴力的解法,然后在看单调栈的解法。 就能感受出单调栈的巧妙
https://programmercarl.com/0739.%E6%AF%8F%E6%97%A5%E6%B8%A9%E5%BA%A6.html
496.下一个更大元素 I
本题和 739. 每日温度 看似差不多,其实 有加了点难度。
https://programmercarl.com/0496.%E4%B8%8B%E4%B8%80%E4%B8%AA%E6%9B%B4%E5%A4%A7%E5%85%83%E7%B4%A0I.htm
单调栈
day57
每日温度
class Solution { public int[] dailyTemperatures(int[] temperatures) { int lens=temperatures.length; int []res=new int[lens]; Deque<Integer> stack=new LinkedList<>(); stack.push(0);//先放进去一个 for(int i=1;i<lens;i++){ if(temperatures[i]<=temperatures[stack.peek()]){ stack.push(i);//温度小于等于就放进栈 }else{ while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){ //温度大就弹出来老数据,记录result,放进栈 res[stack.peek()]=i-stack.peek(); stack.pop(); } stack.push(i); } } return res; } } //发现所有情况都有push操作,优化逻辑 class Solution { public int[] dailyTemperatures(int[] temperatures) { int lens=temperatures.length; int []res=new int[lens]; Deque<Integer> stack=new LinkedList<>(); for(int i=0;i<lens;i++){ while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){ //非公共部分放在上面的代码块里,判断条件是所有其他情况不满足的条件的与 res[stack.peek()]=i-stack.peek(); stack.pop(); } stack.push(i);//公共部分放在下面 } return res; } }
下一个更大元素
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<>();//hashmap放入没有重复元素的num1 for (int i = 0; i < nums1.length; i++) { map.put(nums1[i], i); } int[] res = new int[nums1.length]; Stack<Integer> stack = new Stack<>();//单调栈 Arrays.fill(res, -1); for (int i = 0; i < nums2.length; i++) { //遍历nums2,只在需要更新result2的时候去判断一下nums1的result1需不需要也更新 while (!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) { int pre = nums2[stack.pop()]; if (map.containsKey(pre)) { res[map.get(pre)] = nums2[i]; } } stack.push(i); } return res; } }
感谢大佬分享: