这道题和Daily Temperatures是一样的,寻找一个数右边大于它的最近的数。解法也是一样的,用stack维护单调序列,具体解法可以参考那篇文章。时间复杂度,空间复杂度均为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> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { | |
int n = nums.size(); | |
unordered_map<int, int> map; | |
stack<int> st; | |
for (int i = n - 1; i >= 0; --i) | |
{ | |
while (st.size() && nums[i] > st.top())st.pop(); | |
map[nums[i]] = st.empty() ? -1 : st.top(); | |
st.push(nums[i]); | |
} | |
vector<int> res; | |
for (auto& num : findNums)res.push_back(map[num]); | |
return res; | |
} | |
}; |
No comments:
Post a Comment