当前位置:网站首页>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;
}
}
边栏推荐
- notepad++
- 图神经网络+对比学习,下一步去哪?
- Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
- 【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous
- scipy.misc.imread()
- asp. Net (c)
- Jenkins Pipeline 方法(函数)定义及调用
- Summary of "reversal" problem in challenge Programming Competition
- Applet network data request
- Understanding rotation matrix R from the perspective of base transformation
猜你喜欢

【ManageEngine】如何利用好OpManager的报表功能

信息與熵,你想知道的都在這裏了

Wxss template syntax

AUTOSAR从入门到精通100讲(103)-dbc文件的格式以及创建详解

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

Svgo v3.9.0+

Shutter uses overlay to realize global pop-up

Introduction Guide to stereo vision (2): key matrix (essential matrix, basic matrix, homography matrix)

Creation and reference of applet

Kotlin introductory notes (VII) data class and singleton class
随机推荐
Rebuild my 3D world [open source] [serialization-1]
Meta tag details
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]
信息与熵,你想知道的都在这里了
Blue Bridge Cup provincial match simulation question 9 (MST)
nodejs_ fs. writeFile
2309. 兼具大小写的最好英文字母
Progressive JPEG pictures and related
Hosting environment API
编辑器-vi、vim的使用
AUTOSAR从入门到精通100讲(103)-dbc文件的格式以及创建详解
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
Applet global style configuration window
2310. 个位数字为 K 的整数之和
Information and entropy, all you want to know is here
Kotlin introductory notes (IV) circular statements (simple explanation of while, for)
Applet network data request
Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
C # draw Bezier curve with control points for lattice images and vector graphics
[ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)