Leetcode_#503_下一个更大元素Ⅱ

原题:#503_下一个更大元素Ⅱ
⭐️内容较多,点赞收藏不迷路 ⭐️


  • 使用栈保存尚未发现下一个更大元素的下标
  • 使用模运算实现循环,实际上只需遍历一圈,所以将数组虚拟加大一倍
  • 使用next数组保存下标对应的下一个更大元素
  • 遍历数组,使数组的元素与栈顶的元素相比
    • 若栈顶的元素小于当前元素,则弹出栈顶元素(是数组下标),并保存当前元素的值到next数组中
public int[] nextGreaterElements(int[] nums) {
    int len = nums.length;
    Stack<Integer> pre = new Stack<>();
    int[] next = new int[len];
    Array.fill(next,-1);	//初始化数组的元素值,全为-1
    for (int i = 0; i < n * 2; i++) {
        int num = nums[i % len];
        while (!pre.isEmpty() && nums[pre.peek()] < nums) {
            next[pre.pop()] = num;
        }
        if (i < n) {	//因为最多只需要遍历一圈,所以只需要存一个队列的长度
            pre.push(i);
        }
    }
    return next;
}
原创文章 50 获赞 1 访问量 2905

猜你喜欢

转载自blog.csdn.net/u014642412/article/details/105964812