-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathNextGreaterElementII.java
More file actions
39 lines (35 loc) · 1.11 KB
/
NextGreaterElementII.java
File metadata and controls
39 lines (35 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.Stack;
//leetcode 503
public class NextGreaterElementII {
/*
Using stack
SpaceComplexity o(2n) = o(n)
Time complexity o(n)+o(n) = o(n)
1-Insert elements of the array into stack from the last index
2-check for the next greater element
*/
public int[] nextGreaterElements(int[] nums) {
int[] result = new int[nums.length];
Stack<Integer> stack = new Stack<>();
for(int i=nums.length-1; i>=0; i--){
stack.push(nums[i]);
}
for(int i=nums.length-1; i>=0; i--){
if(nums[i] < stack.peek()){
result[i] = stack.peek();
stack.push(nums[i]);
}else{
while(!stack.isEmpty() && nums[i] >= stack.peek())
stack.pop();
if(!stack.isEmpty()){
result[i] = stack.peek();
stack.push(nums[i]);
}else{
result[i] = -1;
stack.push(nums[i]);
}
}
}
return result;
}
}