问题描述 :
已知长度为n的线性表A采用顺序存储结构,请在应用顺序表ADT的基础上,设计一时间复杂度为0(n)、空间复杂度为0(1)的算法,该算法删除线性表中所有值为item的数据元素。要求:线性表元素个数n很大,而值为item的数据元素个数很少,要求移动元素个数尽量少;删除后的数组元素与原数组元素不必保持顺序一致。
参考函数原型:
//删除线性表中所有值为item的数据元素,时间复杂度为0(n)、空间复杂度为0(1)
template<class ElemType>
void DeleteItem( SqList<ElemType> &A, ElemType item );
输入说明 :
第一行:顺序表A的长度
第二行:顺序表A的数据元素(数据元素之间以空格分隔)
第三行:待删除数据元素
输出说明 :
第一行:删除前的顺序表遍历结果
空行
第二行:删除后的顺序表遍历结果(非空)
empty(空)(在本题目的前提条件下不应该出现,为保证算法的鲁棒性增加的测试数据)
输入范例:
40
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 20 21 22 23 24 25 26 27 28 29 30 1 32 33 34 35 36 37 38 39 1
1
输出范例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 20 21 22 23 24 25 26 27 28 29 30 1 32 33 34 35 36 37 38 39 1
39 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 38 20 21 22 23 24 25 26 27 28 29 30 37 32 33 34 35 36
代码实现:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <stdlib.h>
#include <cmath>
#include <vector>
#include <sstream> //用于ostringstream、istringstream、stringstream这三个类
#include<stack>
#include<vector>
#include<queue>
#include<list>
using namespace std;
template<class ElemType>
void DeleteItem( vector<ElemType> &A, ElemType item ){
int length=A.size();
for(int i=0;i<length;i++)
cout<<A[i]<<' ';
cout<<endl<<endl;
int location=length-1;
if(length!=0){
for(int i=0;i<length;i++){
while(A[location]==item&&length>0) //找到最后一个非item的元素位置
{
length--;
location--;
}
if(length==0) break;
int temp;
if(A[i]==item){
temp=A[location];
A[location]=A[i];
A[i]=temp;
location--;
length--;
}
}
}
if(length==0) cout<<"empty"<<endl;
else {
for(int i=0;i<length;i++)
cout<<A[i]<<" ";
}
}
int main()
{
int length;
cin>>length;
vector<int> A;
int num;
for(int i=0;i<length;i++){
cin>>num;
A.push_back(num);
}
int item;
cin>>item;
DeleteItem(A,item);
return 0;
}