1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int n = nums.size(); stack<int> stk; vector<int> ans(n, -1); for (int i = 0; i < n * 2 - 1; ++i) { int idx = i % n; while (!stk.empty() && nums[stk.top()] < nums[idx]) { ans[stk.top()] = nums[idx]; stk.pop(); } stk.push(idx); } return ans; } };
|