题目链接: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]
- 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
- 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;
-
-
相关阅读:
论文阅读之Syntax Encoding with Application in Authorship Attribution(2018)
算法通关村第十关-白银挑战数组最大K数
uniapp主题切换功能的方式终结篇(全平台兼容)
用winsw将nodejs项目的exe程序安装为服务
NUCLEO-L552ZE SWD外部接口定义
arm-linux 原子操作
Linux安装Zookeeper
智慧wifi平台搭建软件模式
面试官:问你期望的工资是多少,怎么回答最好?
深度学习之使用Milvus向量数据库实战图搜图
-
原文地址:https://blog.csdn.net/tlingyuqi/article/details/136300371