当前位置:网站首页>LeetCode 503. 下一个更大元素 II
LeetCode 503. 下一个更大元素 II
2022-07-05 09:16:00 【Sasakihaise_】
【单调栈】把最后一个元素之前的那些元素先入栈,形成环,再按照单调栈的方法遍历即可:
即对于每个元素i,把栈中比他小的元素全部出栈,此时如果栈顶还有,那么栈顶就是第一个比他大的,如果为空说明没有。最后不要忘了把元素i入栈。
class Solution {
// 单调栈 3:15 3:24
public int[] nextGreaterElements(int[] nums) {
Deque<Integer> stack = new LinkedList();
int i, j, n = nums.length;
for (i = n - 2; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= nums[i]) {
stack.pop();
}
stack.push(nums[i]);
}
int[] ans = new int[n];
for (i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= nums[i]) {
stack.pop();
}
if (stack.isEmpty()) {
ans[i] = -1;
} else {
ans[i] = stack.peek();
}
stack.push(nums[i]);
}
return ans;
}
}
边栏推荐
- nodejs_ 01_ fs. readFile
- Introduction Guide to stereo vision (7): stereo matching
- What is a firewall? Explanation of basic knowledge of firewall
- 520 diamond Championship 7-4 7-7 solution
- Add discount recharge and discount shadow ticket plug-ins to the resource realization applet
- C语言-从键盘输入数组二维数组a,将a中3×5矩阵中第3列的元素左移到第0列,第3列以后的每列元素行依次左移,原来左边的各列依次绕到右边
- c#比较两张图像的差异
- Rebuild my 3D world [open source] [serialization-2]
- Meta tag details
- np.allclose
猜你喜欢
C [essential skills] use of configurationmanager class (use of file app.config)
2020 "Lenovo Cup" National College programming online Invitational Competition and the third Shanghai University of technology programming competition
OpenGL - Lighting
Global configuration tabbar
Svgo v3.9.0+
My experience from technology to product manager
Applet data attribute method
Svg optimization by svgo
信息與熵,你想知道的都在這裏了
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]
随机推荐
Introduction Guide to stereo vision (7): stereo matching
Transfer learning and domain adaptation
Applet data attribute method
Generate confrontation network
Multiple linear regression (gradient descent method)
Golang foundation -- map, array and slice store different types of data
Hi Fun Summer, play SQL planner with starrocks!
Applet network data request
信息与熵,你想知道的都在这里了
scipy.misc.imread()
Talking about label smoothing technology
2020 "Lenovo Cup" National College programming online Invitational Competition and the third Shanghai University of technology programming competition
太不好用了,长文章加图文,今后只写小短文
云计算技术热点
Add discount recharge and discount shadow ticket plug-ins to the resource realization applet
Global configuration tabbar
asp. Net (c)
[beauty of algebra] solution method of linear equations ax=0
Codeworks round 639 (Div. 2) cute new problem solution
一文详解图对比学习(GNN+CL)的一般流程和最新研究趋势