数据结构之,线性表去除等于x的元素

时间:2023-03-10 03:43:13
数据结构之,线性表去除等于x的元素

问题看起来很简单,但是这里有个限制,就是算法的时间复杂度位O(n),空间复杂度为O(1),下面上代码

#include <iostream>
#include <string.h>
#include <time.h>
using namespace std; #define n 100 int main()
{
char SZ[n];
char del;
memset(SZ,'\0',n);
cin>>SZ;
cin>>del;
clock_t start,end;//用于计时
start = clock() ; int length = strlen(SZ);//获取当前字符串长度
int count = ;//计数,当前非del字符的个数
for (int i = ;i < length;i++)
{
if (SZ[i] != del)
{
SZ[count] = SZ[i];
count++;
}
}
length = count;//字符串新的长度 for (int i = ;i < length;i++)
cout<<SZ[i];
end = clock();
cout<<"\n总共花费了"<<(end - start)<<endl;
return ;
}

中间的count设置的很巧妙,我的思维一味的拘束在数组的遍历和模拟删除上面,没有想到这个很直接而且效率也很高的方法啊!!

运行结果:

数据结构之,线性表去除等于x的元素