● 503.下一个更大元素II
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
stack<int> st;
st.push(0);
vector<int> res(nums.size(), -1);
for (int i = 1; i < 2 * nums.size(); i++) {
while (!st.empty() && nums[i % nums.size()] > nums[st.top()]) {
res[st.top()] = nums[i % nums.size()];
st.pop();
}
st.push(i % nums.size());
}
return res;
}
};
● 42. 接雨水
class Solution {
public:
int trap(vector<int>& height) {
vector<vector<int>> dp(height.size(), vector<int>(2, -1));
dp[0][0] = -1;
dp[height.size() - 1][1] = -1;
for (int i = 1; i < height.size(); i ++) {
dp[i][0] = max(height[i - 1], dp[i - 1][0]);
}
for (int i = height.size() - 2; i >= 0; i --) {
dp[i][1] = max(height[i + 1], dp[i + 1][1]);
}
int res = 0;
for (int i = 0; i < height.size(); i ++) {
//printf("%d %d %d\n", dp[i][0], height[i], dp[i][1]);
if (dp[i][0] > height[i] && height[i] < dp[i][1]) {
res += min(dp[i][0], dp[i][1]) - height[i];
}
}
return res;
}
};