• [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;
        }
    }
  • 相关阅读:
    地址栏访问Action,后来方法执行两次
    转:Android中的Selector的用法
    转:android 自定义RadioButton样式
    Android中@id与@+id区别
    INSTALL_PARSE_FAILED_MANIFEST_MALFORMED 错误
    Supervisor
    mysql 赋予权限连接
    定时任务
    git 提交代码五部曲
    Mysql 之事物
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9751217.html
Copyright © 2020-2023  润新知