Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit d75a37b

Browse filesBrowse files
Sean PrashadSean Prashad
Sean Prashad
authored and
Sean Prashad
committed
Add 503_Next_Greater_Element_II.java
1 parent 9bde5d5 commit d75a37b
Copy full SHA for d75a37b

File tree

Expand file treeCollapse file tree

1 file changed

+31
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+31
-0
lines changed
+31Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public int[] nextGreaterElements(int[] nums) {
3+
if (nums == null || nums.length == 0) {
4+
return new int[] {};
5+
}
6+
7+
Stack<Integer> s = new Stack<>();
8+
int n = nums.length;
9+
int[] result = new int[n];
10+
11+
for (int i = n - 1; i >= 0; i--) {
12+
s.push(i);
13+
}
14+
15+
for (int i = n - 1; i >= 0; i--) {
16+
result[i] = -1;
17+
18+
while (!s.isEmpty() && nums[i] >= nums[s.peek()]) {
19+
s.pop();
20+
}
21+
22+
if (!s.isEmpty()) {
23+
result[i] = nums[s.peek()];
24+
}
25+
26+
s.push(i);
27+
}
28+
29+
return result;
30+
}
31+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.