【题目描述】
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] 是如上所述的 下一个更大元素 。
https://leetcode.cn/problems/next-greater-element-i/
【示例】

【代码】admin
思路:基于Hash和循环处理 击败98,52%
package com.company;
import java.util.*;
// 2023-03-01
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len = nums1.length;
int len2 = nums2.length;
int[] res = new int[len];
Arrays.fill(res, -1);
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < len2; i++){
map.put(nums2[i], i);
}
for (int i = 0; i < len; i++){
if (map.containsKey(nums1[i])){
int index = map.get(nums1[i]);
while (index < len2){
if (nums2[index] > nums1[i]){
res[i] = nums2[index];
break;
}
index++;
}
}
}
System.out.println(Arrays.toString(res));
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().nextGreaterElement(new int[]{4,1,2}, new int[]{1,3,4,2} ); // 输出:[-1,3,-1]
new Solution().nextGreaterElement(new int[]{2,4}, new int[]{1,2,3,4} ); // 输出:[3,-1]
}
}
【代码】admin2
思路: 暴破
package com.company;
import java.util.*;
// 2023-03-01
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len = nums1.length;
int len2 = nums2.length;
int[] res = new int[len];
Arrays.fill(res, -1);
for (int i = 0; i < len; i++){
for (int j = 0; j < len2; j++){
int index = j;
if (nums1[i] == nums2[j]){
while (index < len2){
if (nums2[index] > nums1[i]) {
res[i] = nums2[index];
break;
}
index++;
}
}
}
}
System.out.println(Arrays.toString(res));
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().nextGreaterElement(new int[]{4,1,2}, new int[]{1,3,4,2} ); // 输出:[-1,3,-1]
new Solution().nextGreaterElement(new int[]{2,4}, new int[]{1,2,3,4} ); // 输出:[3,-1]
}
}
【代码】单调栈

效率还没有【admin2】高
package com.company;
import java.util.*;
// 2023-03-01
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len = nums1.length;
int len2 = nums2.length;
int[] res = new int[len];
Arrays.fill(res, -1);
Stack<Integer> stack = new Stack<>();
// 存储下一个比自己大的元素
Map<Integer, Integer> map = new HashMap<>();
// 先计算 nums2, 相当于找到每个元素比他自己大的下一个元素
for (int i = 0; i < len2; i++){
int num = nums2[i];
while (!stack.isEmpty() && num > nums2[stack.peek()]){
int tmp = stack.peek();
//此时 tmp < num
map.put(nums2[tmp], num);
stack.pop();
}
stack.push(i);
}
for (int i = 0; i < len; i++){
res[i] = map.getOrDefault(nums1[i], -1);
}
System.out.println(Arrays.toString(res));
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().nextGreaterElement(new int[]{4,1,2}, new int[]{1,3,4,2} ); // 输出:[-1,3,-1]
new Solution().nextGreaterElement(new int[]{2,4}, new int[]{1,2,3,4} ); // 输出:[3,-1]
}
}










