503.下一个更大元素II
题目链接:https://leetcode.cn/problems/next-greater-element-ii/description/
思路:
和496一样的做法,不过这次要对原数组处理一下,在后面再拼接一次原数组。或者采用i%n的形式,即可完成循环。
核心代码:
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n=nums.size();
vector<int> ans(n,-1);
stack<int> st;
for(int i=0;i<2*n-1;i++){
while(!st.empty()&&nums[st.top()%n]<nums[i%n]){
ans[st.top()%n]=nums[i%n];
st.pop();
}
st.push(i);
}
return ans;
}
};
42.接雨水
题目链接:https://leetcode.cn/problems/trapping-rain-water/
思路:
我们考虑每列能接多少雨水,然后统计各列之和即可。
我们发现这样一件事:每列能接的雨水取决于其左侧最高的列和右侧最高那列。这两者的最小值决定了雨水的高度,雨水的底部则是该列的高度。
因此我们可以预处理出每列左右两侧的最大值,最后O(n)扫一遍处理每列雨水高度即可。
核心代码:
class Solution {
public:
int trap(vector<int>& height) {
int n=height.size();
vector<int> lmax(n,0);
vector<int> rmax(n,0);
int maxheight=0;
for(int i=0;i<n;i++){
lmax[i]=maxheight;
maxheight=max(height[i],maxheight);
}
maxheight=0;
for(int i=n-1;i>=0;i--){
rmax[i]=maxheight;
maxheight=max(height[i],maxheight);
}
int len=0;
int ans=0;
for(int i=0;i<n;i++){
len=min(lmax[i],rmax[i])-height[i];
if(len>0) ans+=len;
}
return ans;
}
};
今日总结
这次的题学习时长2h,接雨水思路很妙。
准备论文开题了。