今日任务
739. 每日温度
496.下一个更大元素 I
503.下一个更大元素II
739. 每日温度
题目链接: . - 力扣(LeetCode)
class Solution {public int[] dailyTemperatures(int[] temperatures) {Stack<Integer> stack = new Stack<Integer>();int[] res = 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()]) {int pop = stack.pop();res[pop] = i - pop;}stack.push(i);}}return res;}
}
496.下一个更大元素 I
题目链接: . - 力扣(LeetCode)
class Solution {public int[] nextGreaterElement(int[] nums1, int[] nums2) {Stack<Integer> stack = new Stack<Integer>();HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();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()]) {int top = stack.pop();map.put(nums2[top], nums2[i]);}stack.push(i);}}int[] res = new int[nums1.length];for (int i = 0; i < nums1.length; i++) {res[i] = map.getOrDefault(nums1[i], -1);}return res;}
}
503.下一个更大元素II
题目链接: . - 力扣(LeetCode)
class Solution {public int[] nextGreaterElements(int[] nums) {Stack<Integer> stack = new Stack<Integer>();int[] res = new int[nums.length];stack.push(0);Arrays.fill(res, -1);for (int i = 1; i < 2 * nums.length; i++) {int index = i % nums.length;while (!stack.isEmpty() && nums[index] > nums[stack.peek() % nums.length]) {int top = stack.pop();res[top % nums.length] = nums[index];}stack.push(i);}return res;}
}