503. 下一个更大元素 II
题目连接
笔记
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
stack<int> st;
int size = nums.size();
vector<int> result(size, -1);
st.push(0);
for (int i = 0; i < 2 * nums.size(); i++) {
while (!st.empty() && nums[i % size] > nums[st.top()]) {
result[st.top()] = nums[i % size];
st.pop();
}
st.push(i % size);
}
return result;
}
};
42. 接雨水
题目连接
笔记
class Solution {
public:
int trap(vector<int>& height) {
stack<int> st;
st.push(0);
int sum = 0;
for (int i = 1; i < height.size(); i++) {
while (!st.empty() && height[i] > height[st.top()]) {
int mid = st.top();
st.pop();
if (!st.empty()) {
sum += (min(height[i], height[st.top()]) - height[mid]) * (i - st.top() - 1);
}
}
st.push(i);
}
return sum;
}
};