nums1
中数字 x
的 下一个更大元素 是指 x
在 nums2
中对应位置 右侧 的 第一个 比 x
大的元素。
给你两个 没有重复元素 的数组 nums1
和 nums2
,下标从 0 开始计数,其中nums1
是 nums2
的子集。
对于每个 0 <= i < nums1.length
,找出满足 nums1[i] == nums2[j]
的下标 j
,并且在 nums2
确定 nums2[j]
的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1
。
返回一个长度为 nums1.length
的数组 ans
作为答案,满足 ans[i]
是如上所述的 下一个更大元素 。
示例 1:
1 2 3 4 5 6
| 输入:nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出:[-1,3,-1] 解释:nums1 中每个值的下一个更大元素如下所述: - 4 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。 - 1 ,用加粗斜体标识,nums2 = [1,3,4,2]。下一个更大元素是 3 。 - 2 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。
|
示例 2:
1 2 3 4 5
| 输入:nums1 = [2,4], nums2 = [1,2,3,4]. 输出:[3,-1] 解释:nums1 中每个值的下一个更大元素如下所述: - 2 ,用加粗斜体标识,nums2 = [1,2,3,4]。下一个更大元素是 3 。 - 4 ,用加粗斜体标识,nums2 = [1,2,3,4]。不存在下一个更大元素,所以答案是 -1 。
|
提示:
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
nums1
和nums2
中所有整数 互不相同
nums1
中的所有整数同样出现在 nums2
中
进阶:你可以设计一个时间复杂度为 O(nums1.length + nums2.length)
的解决方案吗?
使用单调栈
ans的大小为nums1的大小,初始化为-1
由于元素不重复,用map存储nums1元素及其下标的映射
只需要遍历nums2的元素,找到元素右边第一个大的元素,如果该元素在nums1存在,获取其下标映射,ans下标的值就是第一个大的元素的值
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
| class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums1.length; i++){ map.put(nums1[i], i); } int[] ans = new int[nums1.length]; Arrays.fill(ans, -1); Stack<Integer> st = new Stack<>(); for(int i = 0; i < nums2.length; i ++){ if(st.isEmpty() || nums2[i] <= st.peek()){ st.push(nums2[i]); }else{ while(!st.isEmpty() && nums2[i] > st.peek()){ int x = st.peek(); if(map.containsKey(x)){ ans[map.get(x)] = nums2[i]; } st.pop(); } st.push(nums2[i]); } } return ans; } }
|