You are given two arrays (without duplicates) nums1
and nums2
where nums1
’s elements are subset of nums2
. Find all the next greater numbers for nums1
's elements in the corresponding places of nums2
.
The Next Greater Number of a number x in nums1
is the first greater number to its right in nums2
. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
思路:这个题目很好,是单调栈的经典题型;找右边第一个比 num[i]要大的数,那么从右边来的比当前num 小的数,就没必要存,stack里面只存比stack peek 大的数,来的数比peak大,那么踢掉peek,同时踢掉的时候记录peek的next great elment就是踢掉的那个值,整个stack就是一个单调递减栈。这题精妙的地方在于,用hashmap去存右边第一个比他大的数的mapping,也就是存右边第一个踢到这个数的num;如果没有人踢他,代表右边没有人比他大;getOrDefault(nums1[i], -1);
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int n = nums1.length;
int[] res = new int[n];
Arrays.fill(res, -1);
HashMap<Integer, Integer> hashmap = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < nums2.length; i++) {
if(stack.isEmpty()) {
stack.push(i);
} else {
while(!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) {
int index = stack.pop();
hashmap.put(nums2[index], nums2[i]);
}
stack.push(i);
}
}
for(int i = 0; i < n; i++) {
if(hashmap.containsKey(nums1[i])) {
res[i] = hashmap.get(nums1[i]);
}
}
return res;
}
}