classSolution { public: vector<int> nextGreaterElements(vector<int>& nums){ vector<int> ans(nums.size(), -1); stack<int> st; int n = nums.size(), to = 2 * nums.size(); for (int i = 0; i < to; i++) { int loc = i % n; while (!st.empty() && nums[st.top()] < nums[loc]) { ans[st.top()] = nums[loc]; st.pop(); } st.push(loc); } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12
from typing importList
classSolution: defnextGreaterElements(self, nums: List[int]) -> List[int]: ans = [-1] * len(nums) st = [] for i inrange(len(nums) * 2): th = i % len(nums) while st and nums[st[-1]] < nums[th]: ans[st.pop()] = nums[th] st.append(th) return ans