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;
        }
    }
  • 相关阅读:
    只会写“Hello World”的菜鸟心声
    新的旅程
    生成[1,2,,3,4,5,6,7,8,9]的随机数组?
    计算java集合中自定义对象出现的次数
    iOS https 证书信任漏洞解决办法
    自定义 URL Scheme 完全指南
    Apple移动设备处理器指令集 armv6、armv7、armv7s及arm64
    url schemes格式错误
    给UITapGestureRecognizer添加tag
    iOS GIF 格式动画 图片显示
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9751217.html
Copyright © 2011-2022 走看看