leetcode 503. Next Greater Element II

来源:互联网 发布:js回调函数如何返回值 编辑:程序博客网 时间:2024/05/16 23:35

题目:

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.
class Solution {public:    vector<int> nextGreaterElements(vector<int>& nums) {        vector<int> fd(nums.size()*2,0);        stack<pair<int,int>> re;        nums.insert(nums.end(), nums.begin(), nums.end());        for(int i = 0; i < nums.size();i++) {            if(re.empty()) {                re.push(pair<int,int>(nums[i],i));            } else {                if(nums[i] < re.top().first) {                    re.push(pair<int,int>(nums[i],i));                } else {                    while(!re.empty()&&nums[i] > re.top().first) {                        fd[re.top().second] = nums[i];                        re.pop();                    }                    re.push(pair<int,int>(nums[i],i));                }            }        }        while(!re.empty()) {            fd[re.top().second] = -1;            re.pop();        }        fd.resize(fd.size()/2);        return fd;    }};


原创粉丝点击