next greater element ii

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,因为可以循环查找,所以最好还需要遍历一遍数组,代码如下:

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def (self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
s, result = [], [-1] * len(nums)
for i in range(len(nums)):
while len(s) and nums[s[-1]] < nums[i]:
result[s[-1]] = nums[i]
s.pop()
s.append(i)
for i in range(len(nums)):
while len(s) and nums[s[-1]] < nums[i]:
result[s[-1]] = nums[i]
s.pop()
return result

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vector<int> nextGreaterElements(vector<int>& nums) {
stack<int> s;
vector<int> result(nums.size(), -1);
for(int i = 0; i < nums.size(); ++i) {
while(!s.empty() && nums[s.top()] < nums[i]) {
result[s.top()] = nums[i];
s.pop();
}
s.push(i);
}
for(int i = 0; i < nums.size() && !s.empty(); ++i) {
while(!s.empty() && nums[s.top()] < nums[i]) {
result[s.top()] = nums[i];
s.pop();
}
}
return result;
}