leetcode503

public class Solution {
    public int[] NextGreaterElements(int[] nums) {
        int n = nums.Length;
            int[] next = new int[n];
            for (int i = 0; i < n; i++)
            {
                next[i] = -1;
            }
            Stack<int> stack = new Stack<int>(); // index stack
            for (int i = 0; i < n * 2; i++)
            {
                int num = nums[i % n];
                while (stack.Count > 0 && nums[stack.Peek()] < num)
                {
                    next[stack.Pop()] = num;
                }
                if (i < n)
                {
                    stack.Push(i);
                }
            }
            return next;
    }
}

https://leetcode.com/problems/next-greater-element-ii/#/solutions

关键的思路是将数组延长到2倍的长度,然后用%运算,将索引缩小到1倍之内进行1倍长度内的判断。

原文地址:https://www.cnblogs.com/asenyang/p/6835710.html