• 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~

     1 class Solution {
     2     private int getNextGreater(int[] nums,int begin,int end,int target)
     3     {
     4         if (begin>nums.length -1 || end>nums.length-1 || begin > end) return Integer.MIN_VALUE;
     5         for (int i=begin;i<=end;i++)
     6         {
     7             if (nums[i] > target) return nums[i];
     8         }
     9         return Integer.MIN_VALUE;
    10     }    
    11     
    12     public int[] nextGreaterElements(int[] nums) {
    13         int[] result = new int[nums.length];
    14         if (nums.length==0) return new int[]{};
    15         if (nums.length ==1) return new int[]{-1};
    16         for (int i=0;i<nums.length;i++)
    17         {
    18             int greaterLeft = Integer.MIN_VALUE;
    19             int greaterRight = Integer.MIN_VALUE;
    20             if (i==0)
    21             {
    22                 greaterRight = getNextGreater(nums,1,nums.length-1,nums[i]);
    23             }else if (i == nums.length-1)
    24             {
    25                 greaterLeft = getNextGreater(nums,0,i-1,nums[i]);
    26             }else
    27             {
    28                 greaterRight = getNextGreater(nums,i+1,nums.length-1,nums[i]);
    29                 if (greaterRight==Integer.MIN_VALUE)
    30                 {
    31                     greaterLeft = getNextGreater(nums,0,i-1,nums[i]);
    32                 }
    33             }
    34             if (greaterRight==Integer.MIN_VALUE && greaterLeft==Integer.MIN_VALUE) result[i] =-1;
    35             else  result[i] = Math.max(greaterLeft,greaterRight);
    36         }
    37         return result;    
    38     }
    39 }
  • 相关阅读:
    arcgis9.3 执行python文件
    python定义影像投影
    要素缩放闪烁功能
    C# Math.Round中国式的四舍五入法
    Eziriz.Net.Reactor使用注意事项
    c# datagridview表格控件常用操作
    主窗口通用泛型打开不同子窗口
    arcgis for android 无法加载本地jpg影像解决办法
    多边形修边算法
    【笔记】Python3导入包规则
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7725860.html
Copyright © 2020-2023  润新知