单调栈
当题目出现「找到最近一个比其大(小)的元素」的字眼时,自然会想到「单调栈」。
具体的,由于我们目标是找到某个数其在 nums2 的右边中第一个比其大的数,因此我们可以对 nums2进行逆序遍历。
我们在遍历 nums2 时,实时维护一个单调栈,当我们遍历到元素 nums2[i] 时,可以先将栈顶中比 nums2[i] 小的元素出栈(因为这些元素已经没有价值了),最终结果有两种可能:
-
栈为空,说明 nums2[i] 之前(右边)没有比其大的数;
-
栈不为空, 此时栈顶元素为 nums2[i] 在 nums2 中(右边)最近的比其大的数。
再利用数组中数值各不相同,在遍历 nums2 的同时,使用哈希表记录每个 nums2[i]对应目标值是多少即可。
//这个题的关键在于如何找到 某个元素对应位置右边第一个比它的元素
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
HashMap<Integer,Integer> map=new HashMap<>();
Deque<Integer> stack=new LinkedList<>();
for(int i=nums2.length-1;i>=0;i--){
while(!stack.isEmpty()&&nums2[i]>stack.peek()){
stack.pop();
}
map.put(nums2[i],stack.isEmpty()?-1:stack.peek());
stack.push(nums2[i]);
}
int[] res=new int[nums1.length];
for(int i=0;i<nums1.length;i++){
res[i]=map.getOrDefault(nums1[i],-1);
}
return res;
}
}
我有一壶酒
足以慰风尘
尽倾江海里
赠饮天下人