zoukankan      html  css  js  c++  java
  • [LeetCode] 503. Next Greater Element II

    Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.

    Example 1:

    Input: [1,2,1]
    Output: [2,-1,2]
    Explanation: The first 1's next greater number is 2; 
    The number 2 can't find next greater number;
    The second 1's next greater number needs to search circularly, which is also 2.

    Note: The length of given array won't exceed 10000.

    题意:给一个循环数组,用另一个数组维护 第一个比当前数大的数字, 若不存在则为-1;

    暴力法就不说了,我们用一个stack来维护下标

    如果nums[s.peek()]的值小于nums[i], res[stack.peek()] = nums[i], s出栈,

    循环两次,第一次全部的i都得进栈

    第一次主要是找后面的,第二次则是找前面的;

    class Solution {
        public int[] nextGreaterElements(int[] nums) {
            int[] res = new int[nums.length];
         
            for (int i = 0; i < nums.length; i++) 
                res[i] = -1;
            
            Stack<Integer> stack = new Stack<>();
            for (int i = 0; i < nums.length; i++) {
                
                while (!stack.empty() && nums[stack.peek()] < nums[i])
                    res[stack.pop()] = nums[i];
                
                stack.push(i);
            }
            for (int i = 0; i < nums.length; i++) {
                
                while (!stack.empty() && nums[stack.peek()] < nums[i])
                    res[stack.pop()] = nums[i];
                
            }
            return res;
        }
    }
  • 相关阅读:
    [蓝桥杯][基础训练]报时助手
    [蓝桥杯][基础训练]分解质因数
    [蓝桥杯][基础训练]2n皇后问题
    [啊哈算法]我要做月老
    [啊哈算法]关键道路(图的割边)
    [啊哈算法]重要城市(图的割点)
    并查集
    栈数组与栈链表代码实现

    循环链表
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9751217.html
Copyright © 2011-2022 走看看