Thursday, August 20, 2020

503. Next Greater Element II -----------M ~~~~

 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.

A:

就是搞一个 increasing stack.  最上面的最小。  唯一的tricky地方就是,  把nums 延展一倍。

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        int n = nums.size();
        vector<int> nums2(nums);
        nums2.insert(nums2.end(), nums.begin(), nums.end());
        
        stack<int> minStack; // top value is always smallest
        vector<int> res(n);
        for(int i= nums2.size()-1;i>=0;i--){
            int val = nums2[i];
            while(not minStack.empty() and minStack.top() <= val){
                minStack.pop();
            }
            if(i<n){
                res[i] = minStack.empty()?-1:minStack.top();
            }
            minStack.push(val);
        }
        return res;
    }
};

Errors:

一开始想nums2中,省掉最后一个, 然而当nums ==[] 时,会报错

        nums2.insert(nums2.end(), nums.begin(), nums.end()-1);


No comments:

Post a Comment