链接:https://leetcode-cn.com/problems/next-greater-element-ii/
单调栈问题,对数组操作两次即可。
java代码:
class Solution {
public int[] nextGreaterElements(int[] nums) {
int [] result = new int[nums.length];
for(int i = 0;i<result.length;i++)
result[i] = -1;
Stack<Integer>stack = new Stack<>();
for(int i = 0;i<nums.length;i++)
{
if(stack.isEmpty())
stack.push(i);
else
{
while(!stack.isEmpty()&&nums[i]>nums[stack.peek()])
{
int temp = stack.pop();
result[temp] = nums[i];
}
stack.push(i);
}
}
for(int i = 0;i<nums.length;i++)
{
if(stack.isEmpty())
stack.push(i);
else
{
while(!stack.isEmpty()&&nums[i]>nums[stack.peek()])
{
int temp = stack.pop();
result[temp] = nums[i];
}
stack.push(i);
}
}
return result;
}
}