496. 下一个更大元素 I
解题思路
- 首先计算nums2的每一个元素的下一个比他大的元素,使用单调栈
- 将上面的结果和nums2中的每一个元素组成映射map
- 针对每一个Nums1的元素 查询map 记录map 的value
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49