Stack
O(n)
- using a stack to remember numbers in descending order from the bottom, once next number is larger than the top element in the stack, pop that top element and save this pair into a map
- using a map, key is the number in the findNums array, value is the next right element got from nums array
public class Solution {
public int[] nextGreaterElement(int[] findNums, int[] nums) {
Stack<Integer> stack = new Stack<>();
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
while (!stack.isEmpty() && stack.peek() < num) {
map.put(stack.pop(), num);
}
stack.push(num);
}
int[] result = new int[findNums.length];
for (int i = 0; i < findNums.length; ++i) {
if (map.containsKey(findNums[i])) {
result[i] = map.get(findNums[i]);
} else {
result[i] = -1;
}
}
return result;
}
}
Improvement
only store the elements that are in findNums array into the map
public class Solution {
public int[] nextGreaterElement(int[] findNums, int[] nums) {
Stack<Integer> stack = new Stack<>();
Map<Integer, Integer> map = new HashMap<>();
for (int num : findNums) {
map.put(num, -1);
}
for (int num : nums) {
while (!stack.isEmpty() && stack.peek() < num) {
map.put(stack.pop(), num);
}
stack.push(num);
}
int[] result = new int[findNums.length];
for (int i = 0; i < findNums.length; ++i) {
result[i] = map.get(findNums[i]);
}
return result;
}
}