[Leetcode] 力扣503:下一个更大元素II

在这里插入图片描述
思路
“下一个更大”问题,既然数组循环就遍历数组两遍保证每个元素后面都有整个数组的元素

class Solution {
    
    
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
    
    
        int n = nums.size();
        stack<int> s;
        vector<int> res(n, -1);
        for (int i = 0; i < 2 * n; ++i) {
    
    
            while (!s.empty() && nums[i % n] > nums[s.top()]) {
    
    
                res[s.top()] = nums[i % n];
                s.pop();
            }
            s.push(i % n);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/112580924