代码随想录算法训练营第五十八天 | 每日温度、下一个更大元素 I
● 今日学习的文章链接和视频链接
● 看到题目的第一想法
有一些难比起普通的栈
● 看完代码随想录之后的想法
看了图之后理解了单调的意思
● 实现过程中遇到哪些困难
第二题题干没看懂
● 解题代码
-
点击查看代码
class Solution { public int[] dailyTemperatures(int[] temperatures) { int len = temperatures.length; int[] result = new int[len]; Deque<Integer> stack=new LinkedList<>(); stack.push(0); for(int i = 1;i < len;i++){ if(temperatures[i] <= temperatures[stack.peek()]){ stack.push(i); }else{ while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){ result[stack.peek()] = i - stack.peek(); stack.pop(); } stack.push(i); } } return result; } } -
点击查看代码
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { HashMap<Integer,Integer> map = new HashMap<>(); 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++){ 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; } }
● 今日收获,学习时长
今日收获:学习了单调栈,假如是单调递增a[i],那么就比较 弹出比他小的a[x] 自己再入栈a[y] 栈里面存的是位置信息i 由此可以得出距离 y - x即可
学习时长:1h
浙公网安备 33010602011771号