503. Next Greater Element II

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

以上是关于503. Next Greater Element II的主要内容,如果未能解决你的问题,请参考以下文章

503. Next Greater Element II

leetcode496 - Next Greater Element I - easy && leetcode503 - Next Greater Element II - medi

[栈] leetcode 503 Next Greater Element II

503. Next Greater Element II

503. Next Greater Element II 下一个更大元素

java 503. Next Greater Element II(1st).java