Input: nums =[2,4,0,9,6]Output: [9,6,6,-1,-1]Explanation:
0th index:4is the first integer greater than 2, and 9is the second integer greater than 2, to the right of 2.1st index:9is the first, and 6is the second integer greater than 4, to the right of 4.2nd index:9is the first, and 6is the second integer greater than 0, to the right of 0.3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.Thus, we return[9,6,6,-1,-1].
We need to find, for each element, the second greater element to its right. This is a monotonic stack problem, but we need to track two levels of “greater”. We can use two stacks: one for first greater, one for second greater.
Iterate through the array. For each index, use two stacks:
The first stack tracks indices waiting for their first greater.
The second stack tracks indices waiting for their second greater.
When a new value is greater than the top of the first stack, move those indices to the second stack. When a new value is greater than the top of the second stack, set answer for those indices.
publicint[]secondGreater(int[] nums) {
int n = nums.length;
int[] res =newint[n];
Arrays.fill(res, -1);
Deque<Integer> st1 =new ArrayDeque<>(), st2 =new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!st2.isEmpty() && nums[i]> nums[st2.peekLast()]) {
res[st2.pollLast()]= nums[i];
}
List<Integer> wait =new ArrayList<>();
while (!st1.isEmpty() && nums[i]> nums[st1.peekLast()]) {
wait.add(st1.pollLast());
}
for (int j = wait.size()-1; j >= 0; j--) st2.addLast(wait.get(j));
st1.addLast(i);
}
return res;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
funsecondGreater(nums: IntArray): IntArray {
val n = nums.size
val res = IntArray(n) { -1 }
val st1 = ArrayDeque<Int>()
val st2 = ArrayDeque<Int>()
for (i in0 until n) {
while (st2.isNotEmpty() && nums[i] > nums[st2.last()]) {
res[st2.removeLast()] = nums[i]
}
val wait = mutableListOf<Int>()
while (st1.isNotEmpty() && nums[i] > nums[st1.last()]) {
wait.add(st1.removeLast())
}
for (j in wait.size-1 downTo 0) st2.addLast(wait[j])
st1.addLast(i)
}
return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defsecondGreater(nums):
n = len(nums)
res = [-1] * n
st1, st2 = [], []
for i, v in enumerate(nums):
while st2 and v > nums[st2[-1]]:
res[st2.pop()] = v
wait = []
while st1 and v > nums[st1[-1]]:
wait.append(st1.pop())
for j in reversed(wait):
st2.append(j)
st1.append(i)
return res