1. 程式人生 > >503. Next Greater Element II(python+cpp)

503. Next Greater Element II(python+cpp)

題目:

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陣列的一般方法就是把陣列變為原來的二倍

,對於這道題,變為原來的二倍之後直接查詢右邊比它大的第一個元素即可,和Next Greater Element I 的方法類似但是不一樣,因為I中元素是不重複的,所以可以用字典做,這個元素是重複的,所以不能用字典做(這字典中存的是元素),但是可以用存陣列下標的字典做,事實上這裡不需要用字典了,直接用棧做就可以了,因為本題是在一個list中完成的,不是I中的兩個list,本道題不是直接將陣列變為二倍,而是將陣列的下標所組成的list變為二倍,因為是要通過下標來尋找元素 python程式碼:

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),注意順序哦。