当前位置:网站首页>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;
}
}
边栏推荐
- np. allclose
- scipy.misc.imread()
- Codeworks round 638 (Div. 2) cute new problem solution
- Information and entropy, all you want to know is here
- C [essential skills] use of configurationmanager class (use of file app.config)
- 3D reconstruction open source code summary [keep updated]
- 【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
- Jenkins Pipeline 方法(函数)定义及调用
- C#绘制带控制点的Bezier曲线,用于点阵图像及矢量图形
- Kotlin introductory notes (VII) data class and singleton class
猜你喜欢

Newton iterative method (solving nonlinear equations)

Understanding rotation matrix R from the perspective of base transformation
![3D reconstruction open source code summary [keep updated]](/img/ec/984aede7ef9e758abd52fb5ff4e144.jpg)
3D reconstruction open source code summary [keep updated]

nodejs_ fs. writeFile
![Rebuild my 3D world [open source] [serialization-2]](/img/e6/aad5f432aca619b992753187729dcf.jpg)
Rebuild my 3D world [open source] [serialization-2]
![Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]](/img/68/6bfa390b0bedcdbc4afba2f9bd9c0f.jpg)
Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]

利用请求头开发多端应用

Priority queue (heap)

Confusion matrix

Applet network data request
随机推荐
Transfer learning and domain adaptation
Luo Gu p3177 tree coloring [deeply understand the cycle sequence of knapsack on tree]
Codeforces Round #648 (Div. 2) D. Solve The Maze
【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
Progressive JPEG pictures and related
图神经网络+对比学习,下一步去哪?
Applet network data request
File server migration scheme of a company
Understanding rotation matrix R from the perspective of base transformation
Applet global style configuration window
2311. 小于等于 K 的最长二进制子序列
Huber Loss
什么是防火墙?防火墙基础知识讲解
np. allclose
Information and entropy, all you want to know is here
Kotlin introductory notes (VI) interface and function visibility modifiers
asp. Net (c)
c语言指针深入理解
Kotlin introductory notes (III) kotlin program logic control (if, when)
Uni app implements global variables