- 下一个更大元素 I
给定两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。
示例 1:
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
示例 2:
输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。
对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。
提示:
nums1和nums2中所有元素是唯一的。
nums1和nums2 的数组大小都不超过1000。
1.暴力方法
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1 = nums1.length, len2 = nums2.length;
if(len1 == 0 || len2 == 0) return new int[]{};
int ans[] = new int[len1];
for(int i = 0; i < len1; i++){
int targ = nums1[i];
boolean flag = false;
int j = 0;
while(j < len2){
if(nums2[j] == targ) break;
j++;
}
for(; j < len2; j++){
if(nums2[j] > targ){
flag = true;
break;
}
}
if(flag) ans[i] = nums2[j];
else ans[i] = -1;
}
return ans;
}
}
2.利用单调栈的方法,这里栈是单调递减的
import java.util.*;
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1 = nums1.length, len2 = nums2.length;
if(len1 == 0 || len2 == 0) return new int[]{};
int ans[] = new int[len1];
Stack<Integer> st = new Stack<>();
HashMap<Integer, Integer> map = new HashMap<>();//建立一个映射
//先对nums2数组集中处理
for(int i = 0; i < len2; i++){
while(!st.isEmpty() && nums2[i] > st.peek()){//这里直接放值
//栈维持的是一个递减的栈,与之前还不太相同
map.put(st.pop(), nums2[i]);
}
st.push(nums2[i]);
}
//对于hash表中没有的,都置为-1
for(int i = 0; i < len1; i++){
ans[i] = map.getOrDefault(nums1[i], -1);
}
return ans;
}
}
3.使用倒序的方法
数组逆序,仍采用单调减栈,当出现当前元素>栈顶元素时,这个时候可以确定该元素的下一个比其大的数值了,只需要不断出栈即可,若栈为空,则为-1,即不存在。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1 = nums1.length, len2 = nums2.length;
if(len1 == 0 || len2 == 0) return new int[]{};
ArrayDeque<Integer> st = new ArrayDeque<>();
HashMap<Integer, Integer> map = new HashMap<>();
//倒着往栈里放
for(int i = len2 - 1; i >= 0; i--){
while(!st.isEmpty() && nums2[i] >= st.peek()){
//转换一下思维
//由于是从后往前,当前的元素只要大于栈顶的元素,一律排出
st.pop();
}
map.put(nums2[i], st.isEmpty() ? -1: st.peek());
st.push(nums2[i]);//仍是放入栈中
}
int[] res = new int[len1];
for(int i = 0; i < len1; i++){
res[i] = map.getOrDefault(nums1[i], -1);
}
return res;
}
}