503. The next element of a larger II
503. Greater the Next Element II
Title Description
Given a loop array (the last element of the next element is the first element of the array), the output of each element of the next higher element. The next element of a larger number x is based on an array traversal order, bigger than its first number after this number, which means that you should search for its next cycle of a larger number. If not, then the output of -1.
LeetCode503. Next Greater Element II中等
Example 1:
Input:
[1,2,1]
Output: [2, 1,2]
Explanation: at first a larger number is 1 2; a larger number can not be found under the numbers 2; the second the next largest number of cycles required 1 search result is 2.
Output: [2, 1,2]
Explanation: at first a larger number is 1 2; a larger number can not be found under the numbers 2; the second the next largest number of cycles required 1 search result is 2.
Note: the length of the input array does not exceed 10000.
Java implementation
brute force
import java.util.Arrays;
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] res = new int[n];
Arrays.fill(res, -1);
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < i + n; j++) {
if (nums[j % n] > nums[i]) {
res[i] = nums[j % n];
break;
}
}
}
return res;
}
}
Stack Stack
import java.util.Arrays;
import java.util.Stack;
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
Stack<Integer> stack = new Stack<>();
int[] res = new int[n];
Arrays.fill(res, -1);
for (int i = 0; i < 2 * n; i++) {
int num = nums[i % n];
while (!stack.isEmpty() && num > nums[stack.peek()]) {
res[stack.pop()] = num;
}
if (i < n) {
stack.push(i);
}
}
return res;
}
}
Similar topics
- 496. Under a greater element I Next Greater Element I
- A next greater element 556. III Next Greater Element III
Reference material