当前位置: 首页 > news >正文

C++滑动门问题(附两种方法)

题目如下:

滑动窗口 - 题目 - Liuser's OJ

——引用自OJ网站

方法如下:

1.常规思想

#include<bits/stdc++.h>
using namespace std;
int main()
{int n,k;int a[110];cin>>n>>k;for(int i=0;i<n;i++){cin>>a[i];}for(int i=0;i<n-k;i++){int ma=-1;for(int j=i;j<i+k;j++){ma=max(ma,a[j]);}cout<<ma<<endl;}return 0;
}

做起来很简单,缺点也很明显

时间复杂度太高

遇到极端数据就会出错

2.栈思想

#include<bits/stdc++.h>
#include<stack>
using namespace std;
int a[110];
int ma[110];
int n,k;
int l=0;
int main()
{stack<int> s;stack<int> ss;cin>>n>>k;for(int i=0;i<n;i++){cin>>a[i];}for(int i=0;i<k;i++){if(s.empty()==true||s.top()<=a[i]){s.push(a[i]);}else if(s.top()>a[i]){int t=0;while(!(s.empty()==true||s.top()<=a[i])){ss.push(s.top());s.pop();t++;}s.push(a[i]);for(int j=0;j<t;j++){s.push(ss.top());ss.pop();}}}ma[++l]=s.top();while(s.empty()!=true){ss.push(s.top());s.pop();}cout<<ss.top()<<" ";while(ss.empty()!=true){s.push(ss.top());ss.pop();}for(int i=k;i<n;i++){while(true){if(a[i-k]==s.top()){s.pop();break;}ss.push(s.top());s.pop();}if(s.empty()==true){s.push(ss.top());ss.pop();}if(a[i]<s.top()){while(true){if(s.empty()==true){s.push(a[i]);break;}if(a[i]<s.top()){ss.push(s.top());s.pop();}else{s.push(a[i]);break;}}}else if(a[i]>=s.top()){if(ss.empty()==true){s.push(a[i]);}else{while(true){if(ss.empty()==true){s.push(a[i]);break;}if(ss.top()<=a[i]){s.push(ss.top());ss.pop();}else{s.push(a[i]);break;}}}}while(ss.empty()!=true){s.push(ss.top());ss.pop();}ma[++l]=s.top();while(s.empty()!=true){ss.push(s.top());s.pop();}cout<<ss.top()<<" ";while(ss.empty()!=true){s.push(ss.top());ss.pop();}}cout<<endl;for(int i=1;i<=l;i++){cout<<ma[i]<<" ";}return 0;
}

虽然写起来有亿点点麻烦,但是胜在稳定

!!!注意  !!!

作者写代码的时候没有注意数据范围,在网站里测试的时候会出错

自己在网站里测试的时候记得根据实际情况调整数据范围!!!!

http://www.xdnf.cn/news/603901.html

相关文章:

  • SmartSoftHelp 之 SQL Server 数据库安全备份与安全还原详解---深度优化版:SmartSoftHelp DeepCore XSuite
  • 运维打铁:生产服务器用户权限管理方案全解析
  • leetcode 3068. 最大节点价值之和
  • 阿里开源 CosyVoice2:打造 TTS 文本转语音实战应用
  • 音视频之视频压缩及数字视频基础概念
  • 看海回测系统回测过程
  • CSS 列表样式完全解析:从 ul/ol 基础到自定义样式
  • Kotlin 中该如何安全地处理可空类型?
  • 计算机图形学:(三)MVP变换扩展
  • WPF骨架屏控件(Skeleton)
  • 阿里巴巴Qwen3技术报告深度解析:开源大模型的最新突破
  • ECharts图表工厂,完整代码+思路逻辑
  • PHP实现签名类
  • Pandas:数据分析中的缺失值检测、加载、设置、可视化与处理
  • 苍穹外卖07 缓存菜品缓存套餐 添加购物车
  • 基于大模型预测发育性髋脱位的多维度研究与应用报告
  • c++面向对象基础学习笔记
  • 信号线上加小pf电容、串接电阻以备滤波、阻抗匹配
  • 基于非线性规划的电动汽车充电站最优布局
  • 华为云Astro前端页面数据模型选型及绑定IoTDA物联网数据实施指南
  • 数据结构第1章 (竟成)
  • 2025年渗透测试面试题总结-匿名[社招]安全工程师(红队方向)2(题目+回答)
  • 02-jenkins学习之旅-基础配置
  • 分布式消息队列kafka详解
  • PHP序列化数据格式详解
  • SpringBoot-10-SpringBoot结合MyBatis操作mysql并提供web服务
  • UE5.1.1 环境下 VS2019 项目跨机运行报错分析
  • 如何将带有LFS对象的git仓库推送到gitlab
  • 《精灵宝可梦特别篇》漫画集 4部合集共76卷,PDF格式分享
  • go 基础语法 【教程 go tour】