739. 每日温度
public int[] dailyTemperatures(int[] T) {Stack<Integer> stack = new Stack<>(); // 创建一个栈来存储索引int length = T.length; // 温度数组的长度int[] result = new int[length]; // 初始化结果数组for (int i = 0; i < length; i++) { // 遍历温度数组// 当栈不为空且当前温度大于栈顶温度while (!stack.isEmpty() && T[i] > T[stack.peek()]) {int pre = stack.pop(); // 弹出栈顶索引result[pre] = i - pre; // 计算天数差并存入结果数组}stack.add(i); // 将当前索引入栈}return result; // 返回结果数组
}
496. 下一个更大元素 I
class Solution {public int[] nextGreaterElement(int[] nums1, int[] nums2) {int n = nums1.length;// 创建一个哈希表,存储 nums1 中元素及其索引Map<Integer, Integer> idx = new HashMap<>(n);for (int i = 0; i < n; i++) {idx.put(nums1[i], i); // nums1 的元素作为键,索引作为值}int[] ans = new int[n]; // 结果数组Arrays.fill(ans, -1); // 初始化结果数组为 -1Deque<Integer> st = new ArrayDeque<>(); // 创建一个栈// 遍历 nums2for (int x : nums2) {// 当栈不为空且当前元素 x 大于栈顶元素while (!st.isEmpty() && x > st.peek()) {// x 是栈顶的下一个更大元素// 记录答案ans[idx.get(st.pop())] = x; // 弹出栈顶元素并记录其下一个更大元素}// 如果 x 在 nums1 中if (idx.containsKey(x)) {st.push(x); // 将 x 入栈}}return ans; // 返回结果数组}
}
503. 下一个更大元素 II
class Solution {public int[] nextGreaterElements(int[] nums) {int n = nums.length; // 获取数组的长度int[] ans = new int[n]; // 初始化结果数组Arrays.fill(ans, -1); // 默认填充为 -1Deque<Integer> st = new ArrayDeque<>(); // 创建一个栈// 遍历数组两次,模拟循环效果for (int i = 0; i < 2 * n; i++) {int x = nums[i % n]; // 当前元素,使用模运算来处理循环// 比较当前元素与栈顶元素while (!st.isEmpty() && x > nums[st.peek()]) {// x 是 nums[st.peek()] 的下一个更大元素ans[st.pop()] = x; // 更新结果数组}// 只在前 n 个元素中入栈if (i < n) {st.push(i); // 将当前索引入栈}}return ans; // 返回结果数组}
}