496. 下一个更大元素 I(栈)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-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、暴力循环:**
思想**
先遍历nums1和nums2找到nums1各个元素在nums2中的位置j,然后再用k遍历j下标之后的位置,如果找到第一个nums2[k]>nums2[j]即可,注意不存在的情况设置flag来标记
代码**
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int[] res = new int[len1];
for(int i = 0; i < len1; i++){
for(int j = 0; j < len2; j++){
int flag = 0;
if(nums1[i] == nums2[j]){
for(int k = j + 1; k < len2; k++){
if(nums2[j] < nums2[k]){
flag = 1;
res[i] = nums2[k];
break;
}
}
if(flag == 0){
res[i] = -1;
}
}
}
}
return res;
}
}
2、栈1**
思想**
类似于打表,先遍历nums2数组将每个字符的下一个更大元素下标存储在record数组,然后遍历nums1数组和nums2数组,找到1在2中的位置,将对应的record传给res数组对应位置即可
代码**
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int[] res = new int[len1];
int[] record = new int[len2];
for(int j = 0; j < len2; j++){
record[j] = -1;
}
Stack<Integer> stack = new Stack<Integer>();
for(int j = 0; j < len2; j++){
while(!stack.isEmpty() && nums2[j] > nums2[stack.peek()]){
record[stack.pop()] = nums2[j];
}
stack.push(j);
}
for(int i = 0; i < len1; i++){
for(int j = 0; j < len2; j++){
int flag = 0;
if(nums1[i] == nums2[j]){
res[i] = record[j];
}
}
}
return res;
}
}
3、栈2**
思想**
与栈1思想类似,但是不用打表,用hashMap直接将nums1中字符对应到遍历nums2数组求得每个字符的下一个更大元素下标
代码**
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int[] res = new int[len1];
Stack<Integer> stack = new Stack<Integer>();
HashMap<Integer, Integer> map = new HashMap<>();
for(int j = 0; j < len2; j++){
while(!stack.isEmpty() && nums2[j] > nums2[stack.peek()]){
map.put(nums2[stack.pop()], nums2[j]);
}
stack.push(j);
}
while(!stack.isEmpty()){//不存在的情形没出栈,赋值为-1
map.put(nums2[stack.pop()], -1);
}
for(int i = 0; i < len1; i++){
res[i] = map.get(nums1[i]);
}
return res;
}
}