This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> nextGreaterElements(vector<int>& nums) { | |
int len = nums.size(), maxIdx = -1; | |
vector<int> next(len); | |
stack<int> st; | |
for(int i = 0; i < 2 * len; ++i) | |
{ | |
int idx = (len - i + len) % len; | |
while(st.size() && st.top() <= nums[idx])st.pop(); | |
next[idx] = st.empty()? -1: st.top(); | |
st.push(nums[idx]); | |
} | |
return next; | |
} | |
}; |
另一种做法,我们找到nums当中的最大数max,然后从max开始从右向左round-robin式地扫一遍就行了。应为max可以当做绝对的右边界,所有的数,要么在其或者其之前的位置找到答案,要不不存在答案。时间复杂度O(n),空间复杂度O(n)。代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> nextGreaterElements(vector<int>& nums) { | |
int len = nums.size(), maxIdx = -1; | |
if(!len)return {}; | |
for(int i = 0; i < len; ++i) | |
maxIdx = maxIdx == -1? i : nums[i] > nums[maxIdx]? i : maxIdx; | |
vector<int> next(len); | |
next[maxIdx] = -1; | |
stack<int> st; | |
for(int i = 0; i < len; ++i) | |
{ | |
int idx = (maxIdx - i + len) % len; | |
while(st.size() && st.top() <= nums[idx])st.pop(); | |
next[idx] = st.empty()? -1: st.top(); | |
st.push(nums[idx]); | |
} | |
return next; | |
} | |
}; |
No comments:
Post a Comment