当前位置:网站首页>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;
}
}
边栏推荐
- Understanding rotation matrix R from the perspective of base transformation
- scipy.misc.imread()
- 太不好用了,长文章加图文,今后只写小短文
- [code practice] [stereo matching series] Classic ad census: (5) scan line optimization
- Hi Fun Summer, play SQL planner with starrocks!
- 520 diamond Championship 7-4 7-7 solution
- Greendao reported an error in qigsaw, could not init daoconfig
- 22-07-04 西安 尚好房-项目经验总结(01)
- C [essential skills] use of configurationmanager class (use of file app.config)
- OpenGL - Coordinate Systems
猜你喜欢
Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
什么是防火墙?防火墙基础知识讲解
Kotlin introductory notes (V) classes and objects, inheritance, constructors
Applet network data request
Applet (global data sharing)
What is a firewall? Explanation of basic knowledge of firewall
Introduction Guide to stereo vision (3): Zhang calibration method of camera calibration [ultra detailed and worthy of collection]
Applet (subcontracting)
[code practice] [stereo matching series] Classic ad census: (6) multi step parallax optimization
Introduction Guide to stereo vision (1): coordinate system and camera parameters
随机推荐
一篇文章带你走进cookie,session,Token的世界
asp. Net (c)
12. Dynamic link library, DLL
Priority queue (heap)
C#图像差异对比:图像相减(指针法、高速)
My experience from technology to product manager
Shutter uses overlay to realize global pop-up
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
AUTOSAR从入门到精通100讲(103)-dbc文件的格式以及创建详解
【ManageEngine】如何利用好OpManager的报表功能
Talking about label smoothing technology
What is a firewall? Explanation of basic knowledge of firewall
Golang foundation - the time data inserted by golang into MySQL is inconsistent with the local time
Codeworks round 639 (Div. 2) cute new problem solution
[ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)
Alibaba's ten-year test brings you into the world of APP testing
STM32简易多级菜单(数组查表法)
云计算技术热点
C # compare the differences between the two images
【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous