写点什么

代码随想录 Day58 - 单调栈(一)

作者:jjn0703
  • 2023-08-26
    江苏
  • 本文字数:1325 字

    阅读完需:约 4 分钟

作业题

739.每日温度

链接: https://leetcode.cn/problems/daily-temperatures/description/

package jjn.carl.dp;
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Deque;import java.util.Scanner;
/** * @author Jjn * @since 2023/8/26 23:19 */public class LeetCode739 { public int[] dailyTemperatures(int[] temperatures) { int length = temperatures.length; int[] result = new int[length]; Deque<Integer> deque = new ArrayDeque<>(); for (int i = 0; i < length; i++) { while (!deque.isEmpty() && temperatures[i] > temperatures[deque.peekLast()]) { Integer index = deque.pollLast(); result[index] = i - index; } deque.offer(i); } return result; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int count = scanner.nextInt(); int[] temperatures = new int[count]; for (int i = 0; i < count; i++) { temperatures[i] = scanner.nextInt(); } int[] dailyTemperatures = new LeetCode739().dailyTemperatures(temperatures); System.out.println(Arrays.toString(dailyTemperatures)); }}
复制代码

496.下一个更大元素 I

链接:https://leetcode.cn/problems/next-greater-element-i/description/

package jjn.carl.dp;
import java.util.*;
/** * @author Jjn * @since 2023/8/26 23:35 */public class LeetCode496 { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<>(); Deque<Integer> stack = new ArrayDeque<>(); for (int i = nums2.length - 1; i >= 0; --i) { int num = nums2[i]; while (!stack.isEmpty() && num >= stack.peek()) { stack.pop(); } map.put(num, stack.isEmpty() ? -1 : stack.peek()); stack.push(num); } int[] res = new int[nums1.length]; for (int i = 0; i < nums1.length; ++i) { res[i] = map.get(nums1[i]); } return res; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); int n = scanner.nextInt(); int[] nums1 = new int[m]; int[] nums2 = new int[n]; for (int i = 0; i < m; i++) { nums1[i] = scanner.nextInt(); } for (int i = 0; i < n; i++) { nums2[i] = scanner.nextInt(); } int[] nextGreaterElement = new LeetCode496().nextGreaterElement(nums1, nums2); System.out.println(Arrays.toString(nextGreaterElement)); }}
复制代码


发布于: 刚刚阅读数: 4
用户头像

jjn0703

关注

Java工程师/终身学习者 2018-03-26 加入

USTC硕士/健身健美爱好者/Java工程师.

评论

发布
暂无评论
代码随想录 Day58 - 单调栈(一)_jjn0703_InfoQ写作社区