Leetcode: 503. 下一个更大元素 II

关键点:

遍历数组nums时,用 for(int i = 0;i < nums.length * 2;i++) 对数组遍历两次,下标index为i对长度len取余,否则会越界。具体见下列代码。

class Solution {    public int[] nextGreaterElements(int[] nums) {        Stack<Integer> st = new Stack<Integer>();        int len = nums.length;        int[] res = new int[len];        Arrays.fill(res,-1);        for(int i = 0;i < len * 2;i++){            int index = i % len;            while(!st.isEmpty() && nums[st.peek()] < nums[index]){                res[st.pop()] = nums[index];            }            st.push(index);        }        return res;    }}