496. Next Greater Element I
Problem-solving ideas
- First calculate the next element larger than each element of nums2, using a monotonic stack
- Combine the above result and each element in nums2 to form a mapping map
- Query the map for each element of Nums1 and record the value of the map
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] greater = nextGreaterElement(nums2);
Map<Integer,Integer> greaterMap = new HashMap<>();
for(int i =0; i < nums2.length; i++){
greaterMap.put(nums2[i],greater[i]);
}
int[] res = new int[nums1.length];
for(int i = 0; i < nums1.length; i++){
res[i] = greaterMap.get(nums1[i]);
}
return res;
}
public int[] nextGreaterElement(int[] nums){
int n = nums.length;
int[] res = new int[n];
Stack<Integer> s = new Stack<>();
for(int i = n - 1; i >= 0; i--){
while(!s.isEmpty() && s.peek() <= nums[i]){
s.pop();
}
res[i] = s.isEmpty() ? -1 : s.peek();
s.push(nums[i]);
}
return res;
}
}