496. Next Greater Element I!
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
// stack, smaller number on the top,
// if push a larger one, pop the small one out
Map<Integer, Integer> memo = new HashMap<>();
Deque<Integer> stack = new LinkedList<>();
for (int num : nums2){
while(stack.size()>0 && stack.peek()<num){
// num is the next greater element of stack.pop();
memo.put(stack.pop(), num);
}
stack.push(num);
}
for(int i = 0; i<nums1.length; i++){
nums1[i]=memo.getOrDefault(nums1[i],-1);
}
return nums1;
}
}
Last updated
Was this helpful?