503. Next Greater Element II(python+cpp)
阿新 • • 發佈:2018-12-14
題目:
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.
解釋: 用棧做 處理circle陣列的一般方法就是把陣列變為原來的二倍
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
stack=[]
_len=len(nums)
result=[-1]*_len
for i in range(_len)*2:
while stack!=[] and nums[i]>nums[stack[-1]]:
result[stack.pop()]=nums[i]
stack.append(i)
return result
c++程式碼:
#include<stack>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
stack<int> _stack;
vector<int> indexs;
vector<int> result(nums.size(),-1);
for(int j=0;j<2;j++)
{
for(int i=0;i<nums.size();i++)
indexs.push_back(i);
}
for (auto i:indexs)
{
while(!_stack.empty() && nums[i]>nums[_stack.top()])
{
result[_stack.top()]=nums[i];
_stack.pop();
}
_stack.push(i);
}
return result;
}
};
總結:
<stack>
的使用,<vector>
的初始化是(n,-1)
,注意順序哦。