|
@@ -0,0 +1,46 @@
|
|
|
|
|
+package leetcode.p496;
|
|
|
|
|
+
|
|
|
|
|
+import java.util.HashMap;
|
|
|
|
|
+import java.util.Map;
|
|
|
|
|
+import java.util.Stack;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * @ProjectName: LeetCode
|
|
|
|
|
+ * @FileName: Solution
|
|
|
|
|
+ * @Author: 杨逸
|
|
|
|
|
+ * @Data:2024/10/15 10:37
|
|
|
|
|
+ * @Description: https://leetcode.cn/problems/next-greater-element-i/description/
|
|
|
|
|
+ *496. 下一个更大元素 I
|
|
|
|
|
+ */
|
|
|
|
|
+public class Solution {
|
|
|
|
|
+ public int[] nextGreaterElement(int[] nums1, int[] nums2) {
|
|
|
|
|
+ //记录索引
|
|
|
|
|
+ Map<Integer,Integer> map = new HashMap<>();
|
|
|
|
|
+ Map<Integer,Integer> nextMaxValueIndex = new HashMap<>();
|
|
|
|
|
+ int[] ans = new int[nums1.length];
|
|
|
|
|
+ Stack<Integer> stack = new Stack<>();
|
|
|
|
|
+
|
|
|
|
|
+ for (int i = 0; i < nums2.length; i++) {
|
|
|
|
|
+ map.put(nums2[i],i); //记录索引
|
|
|
|
|
+ //找下一个更大值的索引
|
|
|
|
|
+ while (!stack.isEmpty() && nums2[i] > nums2[stack.peek()]){
|
|
|
|
|
+ Integer index = stack.pop();
|
|
|
|
|
+ nextMaxValueIndex.put(nums2[index],i);
|
|
|
|
|
+ }
|
|
|
|
|
+ stack.push(i);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ for (int i = 0; i < nums1.length; i++) {
|
|
|
|
|
+ //索引
|
|
|
|
|
+ int index = map.get(nums1[i]);
|
|
|
|
|
+ //下一个更大值的索引
|
|
|
|
|
+ int nextIndex = nextMaxValueIndex.getOrDefault(nums2[index],-1);
|
|
|
|
|
+ if (nextIndex == -1){
|
|
|
|
|
+ ans[i] = -1;
|
|
|
|
|
+ }else {
|
|
|
|
|
+ ans[i] = nums2[nextIndex];
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return ans;
|
|
|
|
|
+ }
|
|
|
|
|
+}
|