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;
        }
    }
  • 相关阅读:
    激活win10系统的方法(亲测)
    java使用jxl,自动导出数据excle,quartz自动发送邮件
    java对接网银支付案例
    将数字转换成Excel表头格式的字母序号
    mysql date_add日期函数的使用
    itext A4纸张横向创建PDF
    Spring 定时器 定时访问数据库并发送邮件
    mvc路由报错
    eval()和$.parseJSON()注意事项
    跨域学习笔记
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9751217.html
Copyright © 2011-2022 走看看