栈
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] results=new int[nums1.length];
Map<Integer,Integer> hash=new HashMap<>();
Deque<Integer> stack=new ArrayDeque<>();
for (int i=0;i<nums2.length;i++){
while(!stack.isEmpty()&&stack.peek()<nums2[i]){
hash.put(stack.pop(),nums2[i]);
}
stack.push(nums2[i]);
}
while (!stack.isEmpty()){
hash.put(stack.pop(),-1);
}
for (int i=0;i<nums1.length;i++){
results[i]=hash.get(nums1[i]);
}
return results;
}
学以致用
- 单调栈的使用