503. 下一个更大元素 II(leetcode)
https://leetcode.cn/problems/next-greater-element-ii/description/
class Solution {
public int[] nextGreaterElements(int[] nums) {
// 成环的单调栈题,思路1:将nums复制一份接在后面,这样便可模拟成环效果
// 如此就成了裸单调栈模版题
int[] numss=new int[nums.length*2];
for(int i=0;i<numss.length;i++)
numss[i]=nums[i%nums.length];
Deque<Integer> st = new ArrayDeque<>();
int[] res = new int[nums.length*2];
Arrays.fill(res,-1);
for(int i=0;i<numss.length;i++)
{
while(!st.isEmpty() && numss[i] > numss[st.peek()])
{
int top=st.pop(); // 栈顶元素下标
res[top]=numss[i]; // 把大值更新为栈顶元素下标的答案
}
st.push(i);
}
return Arrays.copyOf(res, nums.length);
}
}
class Solution {
public int[] nextGreaterElements(int[] nums) {
// 成环的单调栈题,思路1:将nums复制一份接在后面,这样便可模拟成环效果
// 如此就成了裸单调栈模版题
// 思路2:直接使用%取模来模拟成环
Deque<Integer> st = new ArrayDeque<>();
int[] res = new int[nums.length];
Arrays.fill(res,-1);
for(int i=0;i<nums.length*2;i++)
{
while(!st.isEmpty() && nums[i%nums.length] > nums[st.peek()])
{
int top=st.pop(); // 栈顶元素下标
res[top]=nums[i%nums.length]; // 把大值更新为栈顶元素下标的答案
}
st.push(i%nums.length);
}
return res;
}
}