方法:单调栈
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& t) {
int n = t.size();
stack<int> st;
vector<int> res(n, 0);
for (int i = 0; i < n; ++i) {
while (!st.empty() && t[i] > t[st.top()]) {
res[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(n)
方法:单调栈
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
vector<int> res(n, -1);
stack<int> st;
unordered_map<int, int> vis;
for (int i = 0; i < n; ++i) vis[nums1[i]] = i;
st.push(0);
for (int i = 1; i < m; ++i) {
while (!st.empty() && nums2[i] > nums2[st.top()]) {
if (vis.count(nums2[st.top()]) > 0) {
int idx = vis[nums2[st.top()]];
res[idx] = nums2[i];
}
st.pop();
}
st.push(i);
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(n)
方法:暴力
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
vector<int> res(n, -1);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (nums1[i] == nums2[j]) {
for (int k = j; k < m; ++k)
if (nums1[i] < nums2[k]) {
res[i] = nums2[k];
break;
}
}
}
}
return res;
}
};
$时间复杂度O(),空间复杂度O(n)