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 }
复制代码

 

posted @   daniel456  阅读(122)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示