Description
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.
Solution
题目的意思是:
找出数组中每一个数后面第一个大于这个数的数(可循环),不存在为-1
解法:
和Next Greater Element I类似,借助stack,通过比较、入栈和出栈更新数后面第一个大于这个数的数。不同的是不需要map,因为可以循环查找,所以最好还需要遍历一遍数组,代码如下:
|
|
|
|
近期评论