[leetCode刷题笔记]503. Next Greater Element II

来源:互联网 发布:现货黄金软件下载 编辑:程序博客网 时间:2024/06/06 13:20

用一个stack来存储之前的index

要遍历两遍array因为存在循环。

public class Solution {    public int[] nextGreaterElements(int[] nums) {        int n = nums.length;        int[] res = new int[n];        Arrays.fill(res, -1);        // use a stack to store index that value lower than current value        Stack<Integer> index = new Stack<Integer>();        for (int i = 0; i < n * 2; i++) {            int num = nums[i % n];            while (!index.isEmpty() && nums[index.peek()] < num) {                res[index.pop()] = num;            }            // push only in first round            if (i < n) index.push(i);        }        return res;    }}


0 0
原创粉丝点击