为了减少查询的复杂度,引入map。但是对于map的构建的复杂度如何解决呢,引入了栈。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
HashMap<Integer,Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for(int num:nums2){
while(!stack.isEmpty() && stack.peek()<num){
map.put(stack.pop(),num);
}
stack.push(num);
}
int[] res = new int[nums1.length];
for(int i = 0;i<nums1.length;i++){
res[i] = map.getOrDefault(nums1[i],-1);
}
return res;
}
}