题目
给你两个 没有重复元素 的数组 nums1
和 nums2
,其中 nums1
是 nums2
的子集。
请你找出 nums1
中每个元素在 nums2
中的下一个比其大的值。
nums1
中数字 x
的下一个更大元素是指 x
在 nums2
中对应位置的右边的第一个比 x
大的元素。如果不存在,对应位置输出 -1
。
解题思路
常规思路是枚举 nums1
的每个元素,在 nums2
里向右找第一个大于其的值。时间复杂度是O(n*m)。
这题可以提前对 nums2
进行处理,即找到 nums2
里每个元素第一个比其大的值,用 map
映射一下,然后枚举 nums1
的时候,直接从 map
里拿值,即为答案。那么问题就变成了找到 nums2
里每个元素第一个比其大的值。处理方法是用单调栈,把 nums2
从后往前遍历,同时维护一个单调递增的 stack
。在整个过程中, nums2[i]
能入栈的时候,表示栈顶元素 stack.peek()
是第一个大于 nums2[i]
的元素,那么添加一组映射,如果 nums2[i]
入栈时栈为空,则表示没有比他大的数,那么给 nums2[i]
添加一个 -1
的映射。这样的时间复杂度是O(n+m)。
代码
/*
暴力
*/
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int length1 = nums1.length;
int length2 = nums2.length;
int[] ans = new int[length1];
for (int i = 0; i < length1; i++) {
int flag = -1;
for (int j = 0; j < length2; j++) {
if (nums1[i] == nums2[j]) flag++;
if (flag == 0 && nums2[j] > nums1[i]) {
ans[i] = nums2[j];
flag++;
}
}
if (flag != 1) ans[i] = -1;
}
return ans;
}
}
/*
单调栈
*/
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int length1 = nums1.length;
int length2 = nums2.length;
int[] ans = new int[length1];
Map<Integer, Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for (int i = length2 - 1; i >= 0; i--) {
if (stack.empty()) {
stack.push(nums2[i]);
map.put(nums2[i], -1);
} else {
while (!stack.empty() && stack.peek() < nums2[i]) {
stack.pop();
}
if (stack.empty()) map.put(nums2[i], -1);
else map.put(nums2[i], stack.peek());
stack.push(nums2[i]);
}
}
for (int i = 0; i < length1; i++) {
ans[i] = map.get(nums1[i]);
}
return ans;
}
}