当前位置:网站首页>LeetCode 496. 下一个更大元素 I
LeetCode 496. 下一个更大元素 I
2022-07-05 09:16:00 【Sasakihaise_】

【单调栈】从后往前遍历,对于元素i,不断弹出比i小的元素,如果栈不为空,那么栈顶就是第一个比i大的元素,然后把i押入栈。
class Solution {
// 单调栈找右侧第一个大于他的元素
// 1:55 2:14
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Deque<Integer> stack = new LinkedList();
Map<Integer, Integer> map = new HashMap();
for (var i = 0; i < nums2.length; i++) {
map.put(nums2[i], i);
}
int[] arr = new int[nums2.length];
for (var i = nums2.length - 1; i >= 0; i--) {
while (!stack.isEmpty()) {
int top = stack.peek();
if (top > nums2[i]) {
arr[i] = top;
stack.push(nums2[i]);
break;
} else {
stack.poll();
}
}
if (stack.isEmpty()) {
arr[i] = -1;
stack.push(nums2[i]);
}
}
int[] ans = new int[nums1.length];
for (var i = 0; i < nums1.length; i++) {
ans[i] = arr[map.get(nums1[i])];
}
return ans;
}
}
边栏推荐
- OpenFeign
- NIPS2021 | 超越GraphCL,GNN+对比学习的节点分类新SOTA
- Causes and appropriate analysis of possible errors in seq2seq code of "hands on learning in depth"
- STM32简易多级菜单(数组查表法)
- C form click event did not respond
- Introduction Guide to stereo vision (1): coordinate system and camera parameters
- Luo Gu p3177 tree coloring [deeply understand the cycle sequence of knapsack on tree]
- Huber Loss
- Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
- 利用请求头开发多端应用
猜你喜欢
![[code practice] [stereo matching series] Classic ad census: (4) cross domain cost aggregation](/img/d8/7291a5b14160600ba73810e6dd1eb5.jpg)
[code practice] [stereo matching series] Classic ad census: (4) cross domain cost aggregation

nodejs_ fs. writeFile

【阅读笔记】图对比学习 GNN+CL

Kotlin introductory notes (V) classes and objects, inheritance, constructors

一文详解图对比学习(GNN+CL)的一般流程和最新研究趋势

顶会论文看图对比学习(GNN+CL)研究趋势

My experience from technology to product manager

混淆矩阵(Confusion Matrix)

Editor use of VI and VIM

Attention is all you need
随机推荐
nodejs_ 01_ fs. readFile
RT thread kernel quick start, kernel implementation and application development learning with notes
Characteristic Engineering
C # draw Bezier curve with control points for lattice images and vector graphics
NIPS2021 | 超越GraphCL,GNN+对比学习的节点分类新SOTA
Codeworks round 681 (Div. 2) supplement
Wxss template syntax
Shutter uses overlay to realize global pop-up
Confusing basic concepts member variables local variables global variables
Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
浅谈Label Smoothing技术
Add discount recharge and discount shadow ticket plug-ins to the resource realization applet
520 diamond Championship 7-4 7-7 solution
Composition of applet code
Applet (global data sharing)
2310. The number of bits is the sum of integers of K
Progressive JPEG pictures and related
C语言-从键盘输入数组二维数组a,将a中3×5矩阵中第3列的元素左移到第0列,第3列以后的每列元素行依次左移,原来左边的各列依次绕到右边
Nodemon installation and use
Kotlin introductory notes (II) a brief introduction to kotlin functions