#2454
Next Greater Element IV
master · 1660 · lc hard +32 · verified · 41.5% accepted · 749 likes · top 22%
Description
Given a 0-indexed integer array nums, for each element nums[i] find the second next greater element — the first element to the right of the first element that is strictly greater than nums[i] which is itself strictly greater than some element farther to nums[i]'s right.
More precisely, find the value nums[j] where j is the second index after i at which nums exceeds nums[i].
Return an integer array answer where answer[i] is the second next greater element of nums[i], or -1 if it does not exist.
Example 1:
Input: nums = [2,4,0,9,6]
Output: [9,6,6,-1,-1]
Explanation:
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.
1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.
2nd index: 9 is the first, and 6 is 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].
Example 2:
Input: nums = [3,3]
Output: [-1,-1]
Explanation:
We return [-1,-1] since neither integer has any integer greater than it.
Code
1
2
3