503.下一个更大元素II
题目链接/文章讲解/视频讲解:代码随想录
//503.下一个更大元素Ⅱ
vector<int> nextGreaterElements(vector<int>& nums) {
vector<int> vnResult(nums.size() * 2, -1);
vector<int> numsPlus(nums.begin(), nums.end());
numsPlus.insert(numsPlus.end(), nums.begin(), nums.end());
stack<int> st;
st.push(0);
for (int i = 1; i < numsPlus.size(); i++) {
if (numsPlus[i] <= numsPlus[st.top()]) {
st.push(i);
}
else {
while (!st.empty() && numsPlus[i] > numsPlus[st.top()]) {
vnResult[st.top()] = numsPlus[i];
st.pop();
}
st.push(i);
}
}
vnResult.resize(nums.size());
return vnResult;
}
2.本题小节
思考: 本题相较于上一题,步骤基本一样,只是在开始时需要将数组后面扩为一份数组本身,再进行和上一题一样的计算,最后取结果时,只取原本数组大小的结果即为所得。
基本思路:和上一题一样,不再重复。
42. 接雨水
题目链接/文章讲解/视频讲解:代码随想录
1.代码展示
//42.接雨水
int trap(vector<int>& height) {
//if (height.size() <= 2) {
// return 0;
//}
//vector<int> vnMaxLeft(height.size(), 0);
//vector<int> vnMaxRight(height.size(), 0);
//int nResult = 0;
//vnMaxLeft[0] = height[0];
//vnMaxRight[height.size() - 1] = height[height.size() - 1];
//for (int i = 1; i < height.size(); i++) {
// vnMaxLeft[i] = max(vnMaxLeft[i - 1], height[i]);
//}
//for (int i = height.size() - 2; i >= 0; i--) {
// vnMaxRight[i] = max(vnMaxRight[i + 1], height[i]);
//}
//for (int i = 0; i < height.size(); i++) {
// if (i == 0 && i == height.size() - 1) continue;
// nResult += min(vnMaxLeft[i], vnMaxRight[i]) - height[i];
//}
//return nResult;
if (height.size() <= 2) {
return 0;
}
stack<int> st;
st.push(0);
int nResult = 0;
for (int i = 1; i < height.size(); i++) {
if (height[i] < height[st.top()]) {
st.push(i);
}
else if (height[i] == height[st.top()]) {
st.pop();
st.push(i);
}
else {
while (!st.empty() && height[i] > height[st.top()]) {
int mid = st.top();
st.pop();
if (!st.empty()) {
int h = min(height[st.top()], height[i]) - height[mid];
int w = i - st.top() - 1;
nResult += h * w;
}
}
st.push(i);
}
}
return nResult;
}
2.本题小节
思考:本题将双指针法和单调栈法都做了一遍,双指针法的主要思路是按列进行计算,提前将每个元素左右两边的最大元素确定下来,再计算,本题重点要讲的是单调栈思路。单调栈中,从栈头到栈尾按照从小到大的元素来排列,因此分为三种情况,当height[i] < height[st.top()]时,将i放入栈中,等于时,先pop,再push i,大于时,此时开始计算雨水的面积,每次是按照行来进行计算的,知道height[i] < height[st.top()]时,再push i,这个过程中将雨水面积累加起来即可。
基本思路:注意三种情况的处理思路,尤其是计算雨水面积的情况。