LeetCode 503

503. 下一个更大元素 II

本题同739,循环数组只需要遍历两次即可,特别注意,在进栈的时候,要判断下标是否在范围内!

Java

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        Stack<Integer> st = new Stack<>();
        int[] res = new int[nums.length];
        Arrays.fill(res,-1);
        for(int i = 0 ;i < 2*nums.length;i++){
            while(!st.isEmpty()&&nums[i%nums.length]>nums[st.peek()]){
                int x = st.pop();
                res[x] = nums[i%nums.length];
            }
            if(i<nums.length) st.push(i);//注意
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/xkf97/p/13138320.html