实现思路:

  • 首先忽略nums1数组,只看nums2数组。
    • 对nums2利用单调栈的性质来求解当前数字的下一个较大的数字。
    • 如果当前栈为空 或者 栈顶元素的值 <= 当前元素的值 当前元素直接入栈
    • 如果当前栈不为空 并且 栈顶元素的值 > 当前元素的值 将栈顶元素弹出,那么栈顶元素的下一个较大的元素就是当前元素。 一直弹到不满足条件为止。
    • 如果当前元素循环完毕,并且栈不为空,那么说明栈中的元素都没有比他大的元素,赋值-1。
  • 现在根据nums2的值, 用map.get()来找出对应的下一个更大的元素。
class Solution {
   
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
   
        Stack<Integer> stack = new Stack<>();
        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0; i<nums2.length; i++){
   
            while(!stack.isEmpty() && nums2[i] > stack.peek()){
   
                map.put(stack.pop(), nums2[i]);
            }
            stack.push(nums2[i]);
        }
        while(!stack.isEmpty()){
   
            map.put(stack.pop(), -1);
        }
        int []res = new int[nums1.length];
        for(int i=0; i<nums1.length; i++){
   
            res[i] = map.get(nums1[i]);
        }
        return res;
    }
}