Stack and HashMap
From https://leetcode.com/problems/next-greater-element-i/#/description
public class Solution {
public int[] nextGreaterElement(int[] findNums, int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>(); // ***
Stack<Integer> stack = new Stack<>(); // ****
for(int num : nums){
while(!stack.isEmpty() && stack.peek() < num){ // stack.peek()
map.put(stack.pop(), num); // ** map.put(x), stack.pop()
}
stack.push(num); // stack.push(x)
}
for(int i = 0; i< findNums.length ; i++){
if (map.get(findNums[i]) != null){ // map.get(x) != null // if key doesn't exist
findNums[i] = map.get(findNums[i]);
}else {
findNums[i] = -1;
}
}
return findNums;
}
}