码迷,mamicode.com
首页 > 其他好文 > 详细

503. Next Greater Element II

时间:2017-10-24 22:46:06      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:int   xpl   public   含义   ever   result   exist   题目   class   

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

标签:int   xpl   public   含义   ever   result   exist   题目   class   

原文地址:http://www.cnblogs.com/wzj4858/p/7725860.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!