方法:单调栈
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, -1);
stack<int> st;
st.push(0);
for (int i = 1; i < n * 2; ++i) {
while (!st.empty() && nums[i%n] > nums[st.top()]) {
res[st.top()] = nums[i%n];
st.pop();
}
st.push(i%n);
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(n);
方法:双指针(超时版)
class Solution {
public:
int trap(vector<int>& height) {
int res = 0, n = height.size();
for (int i = 0; i < height.size(); ++i) {
int rmax = height[i], lmax = height[i];
for (int j = i + 1; j < n; ++j) if (rmax < height[j]) rmax = height[j];
for (int j = i - 1; j >= 0; --j) if (lmax < height[j]) lmax = height[j];
res += min(rmax, lmax) - height[i];
}
return res;
}
};
$时间复杂度O(),空间复杂度O(1);
优化:
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
if (n <= 2) return 0;
vector<int> rmax(n, 0);
vector<int> lmax(n, 0);
lmax[0] = height[0];
for (int i = 1; i < n; ++i) {
lmax[i] = max(lmax[i-1], height[i]);
}
rmax[n-1] = height[n-1];
for (int i = n - 2; i >= 0; --i) {
rmax[i] = max(rmax[i+1], height[i]);
}
int res = 0;
for (int i = 0; i < n; ++i) {
res += min(rmax[i], lmax[i]) - height[i] > 0 ? min(rmax[i], lmax[i]) - height[i] : 0;
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(n);
方法:单调栈
class Solution {
public:
int trap(vector<int>& height) {
stack<int> st;
st.push(0);
int res = 0, n = height.size();
for (int i = 1; i < n; ++i) {
while (!st.empty() && height[i] > height[st.top()]) {
int mid = st.top();
st.pop();
if (!st.empty()) {
int w = i - st.top() - 1;
int h = min(height[st.top()], height[i]) - height[mid];
res += w * h;
}
}
st.push(i);
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(n);