503. Next Greater Element II
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public int[] nextGreaterElements(int[] nums) {
if(nums == null || nums.length == 0) {
return new int[0];
}
int n = nums.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
Arrays.fill(result, -1);
for(int i = 0; i < 2*n; i++) {
while(!stack.isEmpty() && nums[stack.peek()] < nums[i%n]) {
result[stack.pop()] = nums[i%n];
}
if(i < n) {
stack.push(i);
}
}
return result;
}
}