Here's the solution:
function nextGreaterElement(nums1, nums2)
nextGreater := empty hash map
stack := empty stack
for each num in nums2
while stack is not empty and num > top of stack
popped := pop from stack
nextGreater[popped] := num
push num onto stack
result := array of size length of nums1
for i from 0 to length of nums1 - 1
if nums1[i] in nextGreater
result[i] := nextGreater[nums1[i]]
else
result[i] := -1
return result
Time: . Space: .