Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. 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, output -1 for this number.
Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
// solution 1 : a working solution
typical way to solve circular array problems is to extend the original array to twice length, 2nd half has the same element as first half.
class Solution {
public int[] nextGreaterElements(int[] nums) {
// 6 4 5 1 2 1 , 6 4 5 1 2 1
// -1 5 5 2 6 6
// add anothe array of the same value
// traverse the original array, and look for the next element in the new combined array
// if not found until found itself again, return -1, break
int[] newArray = new int[nums.length * 2];
for(int i = 0; i < nums.length; i++){
newArray[i] = nums[i];
}
for(int i = nums.length; i < newArray.length; i++){
newArray[i] = nums[i - nums.length];
}
int[] res = new int[nums.length];
for(int i = 0; i < nums.length; i++){
res[i] = helper(newArray, nums[i], i);
}
return res;
}
private int helper(int[] newArray, int num, int index){
for(int i = index + 1; i < newArray.length; i++){
if(newArray[i] > num){
return newArray[i];
}
}
return -1;
}
}
// use stack
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Stack<Integer> stack = new Stack<>();
// like in solution1 , extend the num by length * 2
// push the nums into the stack from 1 to 6
// original array : 6 4 5 1 2 1
// same process as we did in solution when using a stack
for(int i = nums.length - 1; i >= 0; i--){
stack.push(nums[i]);
}
for(int i = nums.length - 1; i >= 0; i--){
while(!stack.isEmpty() && stack.peek() <= nums[i]){ // = also included, same element, also returns -1
stack.pop();
}
if(stack.isEmpty()){
res[i] = -1;
}else{
res[i] = stack.peek();
}
stack.push(nums[i]);
}
return res;
}
}
来源:https://www.cnblogs.com/tobeabetterpig/p/9933768.html