1201. Next Greater Element II
class Solution {
public:
    /**
     * @param nums: an array
     * @return: the Next Greater Number for every element
     */
    vector<int> nextGreaterElements(vector<int> &nums) {
        // Write your code here
        const int n = nums.size(); 
        vector<int> res(n, -1);
        std::stack<int> stk;
        for(int i = 0; i < 2 * n; i++){
            while(!stk.empty() && nums[stk.top()] < nums[i % n]){
                res[stk.top()] = nums[i % n];
                stk.pop(); 
            }
            stk.push(i % n); 
        }
        return res; 
    }
};
Comments
Post a Comment