思路:
// @Title: 下一个更大元素 I (Next Greater Element I)
// @Author: qisiii
// @Date: 2024-06-24 17:54:46
// @Runtime: 3 ms
// @Memory: 43.5 MB
// @comment:
// @flag:
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
LinkedList<Integer> stack=new LinkedList<>();
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums2.length;i++){
int max=-1;
while(!stack.isEmpty()&&stack.peek()<nums2[i]){
int old= stack.pop();
//寻找右侧大就是被弹出时要插入的那个值
map.put(old,nums2[i]);
}
stack.push(nums2[i]);
}
int[] res=new int[nums1.length];
for(int i=0;i<nums1.length;i++){
int value=map.getOrDefault(nums1[i],-1);
res[i]=value;
}
return res;
}
}
+++ title = “下一个更大元素 I (Next Greater Element I)” draft = false +++
思路:
// @Title: 下一个更大元素 I (Next Greater Element I)
// @Author: qisiii
// @Date: 2024-06-24 17:54:35
// @Runtime: 7 ms
// @Memory: 43.5 MB
// @comment:
// @flag:
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
LinkedList<Integer> stack=new LinkedList<>();
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums2.length;i++){
int max=-1;
while(!stack.isEmpty()&&stack.peek()<nums2[i]){
int old= stack.pop();
//寻找右侧大就是被弹出时要插入的那个值
map.put(old,nums2[i]);
}
stack.push(nums2[i]);
}
System.out.println(stack);
System.out.println(map);
int[] res=new int[nums1.length];
for(int i=0;i<nums1.length;i++){
int value=map.getOrDefault(nums1[i],-1);
res[i]=value;
}
return res;
}
}