MrainW's Home

All things come to those who wait!

0%

LeetCode 503. Next Greater Element II

Question

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, return -1 for this number.

https://leetcode.com/problems/next-greater-element-ii/

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length, res[] = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 2 * n - 1; i >= 0; i--){
while (!stack.isEmpty() && nums[i % n] >= stack.peek()) stack.pop();
res[i % n] = stack.isEmpty() ? -1 : stack.peek();
stack.push(nums[i % n]);
}
return res;
}
}

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels