当前位置:网站首页>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;
}
}
边栏推荐
- Talking about the difference between unittest and pytest
- Introduction Guide to stereo vision (1): coordinate system and camera parameters
- 顶会论文看图对比学习(GNN+CL)研究趋势
- C # draw Bezier curve with control points for lattice images and vector graphics
- 信息与熵,你想知道的都在这里了
- Pearson correlation coefficient
- C [essential skills] use of configurationmanager class (use of file app.config)
- OpenGL - Coordinate Systems
- File server migration scheme of a company
- AUTOSAR from getting started to mastering 100 lectures (103) -dbc file format and creation details
猜你喜欢
Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
Kotlin introductory notes (II) a brief introduction to kotlin functions
Confusion matrix
nodejs_ 01_ fs. readFile
优先级队列(堆)
Solution to the problems of the 17th Zhejiang University City College Program Design Competition (synchronized competition)
2020 "Lenovo Cup" National College programming online Invitational Competition and the third Shanghai University of technology programming competition
【ManageEngine】如何利用好OpManager的报表功能
Introduction Guide to stereo vision (3): Zhang calibration method of camera calibration [ultra detailed and worthy of collection]
Applet customization component
随机推荐
C form click event did not respond
Codeforces Round #648 (Div. 2) E.Maximum Subsequence Value
Introduction Guide to stereo vision (1): coordinate system and camera parameters
顶会论文看图对比学习(GNN+CL)研究趋势
c语言指针深入理解
2311. Longest binary subsequence less than or equal to K
高性能Spark_transformation性能
Multiple linear regression (gradient descent method)
云计算技术热点
嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!
notepad++
Characteristic Engineering
Applet global style configuration window
优先级队列(堆)
利用请求头开发多端应用
Driver's license physical examination hospital (114-2 hang up the corresponding hospital driver physical examination)
Add discount recharge and discount shadow ticket plug-ins to the resource realization applet
Oracle advanced (III) detailed explanation of data dictionary
My experience from technology to product manager
Analysis of eventbus source code