zoukankan      html  css  js  c++  java
  • 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.
    class Solution {
        public int[] nextGreaterElements(int[] nums) {
            int le = nums.length;
            int[] arr = new int[le * 2];
            int[] res = new int[le];
            Arrays.fill(res, -1);
            if(le == 0 || nums == null) return new int[0];
            for(int i = 0; i < le; i++) arr[i] = nums[i];
            for(int i = le; i < 2 * le; i++) arr[i] = nums[i - le];
            for(int i = 0; i < le; i++){
                for(int j = i + 1; j < 2 * le; j++){
                    if(arr[j] > nums[i]){ res[i] = arr[j]; break;}
                    
                }
            }
            return res;
        }
    }

    扩充下数组即可

    class Solution {
        public int[] nextGreaterElements(int[] nums) {
            int n = nums.length;
            Stack<Integer> stack = new Stack();
            int res[] = new int[n];
            Arrays.fill(res, -1);
            
            for(int i = 0; i < 2 * n; i++) {
                int cur = nums[i % n];
                while(!stack.isEmpty() && nums[stack.peek()] < cur) {
                    res[stack.pop()] = cur;
                }
                if(i < n) stack.push(i);
            }
            return res;
        }
    }

    用stack存放decreasing subsequence的index,如果对应的num小于当前的cur,说明cur就是next greater。记得初始化-1。

  • 相关阅读:
    java System.getProperty()参数大全
    元类(转自https://zhuanlan.zhihu.com/p/23887627)
    正则(高级)(转)
    正则(转)
    机器学习入门之房价预测(线性回归)
    python字节码(转)
    在虚拟机中搭建django,通过外网访问
    django框架入门
    linux下创建虚拟环境(转)
    PAT1005
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11955510.html
Copyright © 2011-2022 走看看