代码随想录算法训练营第四十五天-739每日温度、496下一个更大元素 I、503下一个更大元素II
初步题解
739 每日温度
题目链接:(https://leetcode.cn/problems/daily-temperatures)
496 下一个更大元素 I
题目链接:(https://leetcode.cn/problems/next-greater-element-i)
503 下一个更大元素 II
题目链接:(https://leetcode.cn/problems/next-greater-element-ii)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public static int[] nextGreaterElements(int[] nums) { int[] result = new int[nums.length]; Arrays.fill(result, -1); Stack<Integer> stack = new Stack<>(); stack.push(0); for (int i = 0; i < nums.length * 2; i++) { while (!stack.isEmpty() && nums[i % nums.length] > nums[stack.peek()]) { result[stack.peek()] = nums[i % nums.length]; stack.pop(); } stack.push(i % nums.length); } return result; }
|
看解析
739 每日温度
解析:(https://programmercarl.com/0739.每日温度.html)
-
情况一:当前遍历的元素 T[i]
小于栈顶元素 T[st.top()]
的情况
-
情况二:当前遍历的元素 T[i]
等于栈顶元素 T[st.top()]
的情况
-
情况三:当前遍历的元素 T[i]
大于栈顶元素 T[st.top()]
的情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public static int[] dailyTemperatures(int[] temperatures) { Deque<Integer> stack = new LinkedList<>(); int[] result = new int[temperatures.length]; stack.push(0); for (int i = 1; i < temperatures.length; 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; }
public int[] dailyTemperatures(int[] temperatures) { Deque<Integer> stack = new LinkedList<>(); int[] result = new int[temperatures.length]; stack.push(0); for (int i = 1; i < temperatures.length; i++) { while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { result[stack.peek()] = i - stack.peek(); stack.pop(); } stack.push(i); } return result; }
|
496 下一个更大元素 I
解析:(https://programmercarl.com/0496.下一个更大元素I.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public int[] nextGreaterElement(int[] nums1, int[] nums2) { int[] result = new int[nums1.length]; Stack<Integer> stack = new Stack<>(); Arrays.fill(result, -1); HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums1.length; i++) { map.put(nums1[i], i); } stack.push(0); for (int i = 1; i < nums2.length; i++) { if (nums2[i] <= nums2[stack.peek()]) { stack.push(i); } else { while (!stack.isEmpty() && nums2[i] > nums2[stack.peek()]) { if (map.containsKey(nums2[stack.peek()])) { result[map.get(nums2[stack.peek()])] = nums2[i]; } stack.pop(); } stack.push(i); } } return result; }
|
503 下一个更大元素 II
解析:(https://programmercarl.com/0503.下一个更大元素II.html)