    class Solution {
        public int[] nextGreaterElement(int[] nums1, int[] nums2) {
            int size = nums1.length;
            int[] result = new int[size];
            Stack<Integer> stack = new Stack<>();
            for (int i = size - 1; i >= 0; i--) {
                result[i] = -2;
                stack.push(nums1[i]);
            }
            int length = nums2.length;
            int index = 0;
            while (!stack.isEmpty()) {
                int i;
                for (i = 0; i < length; i++) {
                    if (result[index] == -2 && nums2[i] == stack.peek()) {
                        result[index] = -1;
                    } else if (result[index] == -1 && nums2[i] > stack.peek()) {
                        result[index] = nums2[i];
                        stack.pop();
                        break;
                    }
                }
                if (i == length && stack.peek() != result[index]) {
                    stack.pop();
                }
                index++;
            }
            return result;
        }
    }

//runtime:40 ms
//memory:38.7 MB
