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。

  • 相关阅读:
    mysql索引批量在postgres里面重建
    获取metabase用户信息
    metabase一个sql统计
    C笔记-左值与右值
    前端散记(不定时补充)
    推荐一本书 保险进行时
    怎么增加照片的KB大小
    Java 流(Stream)、文件(File)和IO
    Java HashMap 和 ConcurrentHashMap 以及JDK 1.7 和 1.8 的区别
    【一文整理:Google Big table 序列化组件 Protocol Buffers 的使用 】
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11955510.html
Copyright © 2011-2022 走看看