zoukankan      html  css  js  c++  java
  • 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 public class Solution {
     2     public int[] nextGreaterElements(int[] nums) {
     3         int n = nums.length;
     4         int[] result = new int[n];
     5         
     6         Stack<Integer> stack = new Stack<>();
     7         for (int i = n - 1; i >= 0; i--) {
     8             if (stack.isEmpty()) {
     9                 result[i] = getValue(nums, i, i);
    10             } else {
    11                 if (nums[i] >= stack.peek()) {
    12                     while (!stack.isEmpty() && stack.peek() <= nums[i]) {
    13                         stack.pop();
    14                     }
    15                     if (stack.isEmpty()) {
    16                         result[i] = getValue(nums, n - 1, i);
    17                         stack.push(nums[i]);
    18                         continue;
    19                     }
    20                 }
    21                 result[i] = stack.peek();
    22             }
    23             stack.push(nums[i]);
    24         }
    25         return result;
    26     }
    27     
    28     private int getValue(int[] nums, int start, int i) {
    29         int n = nums.length, index = (start + 1) % n;
    30         while (index != i) {
    31             if (nums[index] > nums[i]) return nums[index];
    32             index = (index + 1) % n;
    33         }
    34         return -1;
    35     }
    36 }
  • 相关阅读:
    01背包
    用动态规划求两个自然数的最大公约数
    编程实现文件的复制功能,要求源文件名及目标文件名在程序运行后根据提示输入
    this和super
    JAVA中static的使用
    结构化异常处理 笔记
    继承和多态 笔记
    javascript 客户端验证和页面特效制作 学习笔记
    定义封装的类类型 笔记
    C# 核心编程结构Ⅱ 笔记
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6439912.html
Copyright © 2011-2022 走看看