1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int n = nums.size(); if (n == 0) return {}; stack<int> st; vector<int> res(n, -1);
int maxValue = nums[0], maxValueFreq = 0; for (int i = 1; i < n; i++) if (nums[i] > maxValue) maxValue = nums[i]; for (int i = 0; i < n; i++) if (nums[i] == maxValue) maxValueFreq++;
for (int i = 0; i < n; i++) { while (!st.empty() && nums[i] > nums[st.top()]) { if (res[st.top()] == -1) res[st.top()] = nums[i]; st.pop(); } st.push(i); if (i == n - 1) { if (nums[i] == maxValue) break; else i = -1; } if (st.size() == maxValueFreq + 1 && nums[st.top()] == maxValue) break; }
return res; } };
|