C++双指针算法例题

有序数组去重

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
long long a[10000010];
int n,s=0;
int main()
{
	
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>a[i];
		
	}
	for(int f=0;f<n;f++){
		if(a[s]!=a[f]){
			a[++s]=a[f];
		}
	}
	s++;
	for(int i=0;i<s;i++){
		cout<<a[i];
	}
	return 0;
}

移除元素

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
long long a[10000010];
int n,s=0,k;
int main()
{
	
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>a[i];
		
	}
	cin>>k;
	for(int f=0;f<n;f++){
		if(k!=a[f]){
			a[s++]=a[f];
		}
	}
	for(int i=0;i<s;i++){
		cout<<a[i];
	}
	cout<<endl;
	return 0;
}

无重复字符最长字串

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int cnt[130]={0};
bool ifcf();
int main()
{
	string a;
	cin>>a;
	int n=a.size();
	int ma=-1;
	string mas="";
	int s=0,f=0;
	while(true){
		while(true){
			cnt[a[f]]++;
			
			if(cnt[a[f]]>1) break;
			else ma=max(ma,f-s+1);
			f++;
		}
		while(true){
			cnt[a[s]]--;
			s++;
			if(ifcf()==true) break;
		}
	}
	
	return 0;
}
bool ifcf(){
	for(int i=97;i<122;i++){
		if(cnt[i]>1) return false;
	}
	return true;
}
相关推荐
无线通信科研笔记3 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
mmmmath_34 小时前
二叉树の递归遍历
算法
All for pursuit.5 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
小师兄吃牛肉5 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
WL学习笔记6 小时前
日期类(C++)
开发语言·c++·日期类实现
H.莓飛7 小时前
【C++】命名空间、缺省参数、函数重载与引用
linux·开发语言·c++·visual studio
一只小小的芙厨7 小时前
【线性DP】
学习·算法·动态规划
xxwl5857 小时前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构
奋发向前wcx7 小时前
CSP-J复赛模拟赛5 王晨旭补题 2026.10.5
算法
汉克老师8 小时前
GESP2026年9月认证C++八级( 第一部分选择题(1~7题)精讲
c++·gesp·小学生·学c++编程