在中兴笔试中,有一题目要求,去除正整数序列数组中的重复元素,且不改变元素原来位置,例如 arr [] = {1,2,3,4,1,2,3,4} 输出为{1,2,3,4}.再例如arr[] = {1,2,2,2,3,3,4,4,5,5,1,1,1,4,4,4,5,5,6,6}
输出为{1,2,3,4,5,6}
在hash_set中,可以保证元素的唯一性,但是不能够保证元素的顺序,故此题不能采用hash_set解决。
#include <iostream>
#include <vector>
#include <set>
#include <hash_set>
using namespace std ;
int main()
{
int arr[] = {1,1,2,2,3,3,4,4,5,5,6,6,1,0,88,99,5,77};
int arrLength = sizeof(arr)/sizeof(arr[0]);
/*
数组元素输出
*/
cout<<" the arr is : "<< endl;
for (int i = 0 ; i < arrLength ; i++)
{
cout<< arr[i]<< " ";
}
cout<<endl;
/*
容器输出
*/
cout<<"the vector test:"<<endl;
vector<int> vec(arr,arr+arrLength) ;
vector<int>::iterator vecIt ;
for (vecIt =vec.begin();vecIt != vec.end();vecIt++)
{
cout<<*vecIt<<" ";
}
cout<<endl;
/*
set集合
*/
set<int> s ;
set<int>::iterator setIterator ;
for (vecIt = vec.begin() ; vecIt != vec.end();vecIt++)
{
s.insert(*vecIt);
}
cout<< "set test :"<< endl;
for(setIterator = s.begin();setIterator != s.end();setIterator++){
cout<<*setIterator<<" " ;
}
cout<<endl;
/*
hash_set集合元素
*/
hash_set<int> hs ;
hash_set<int>::iterator hash_setInterator ;
for (vecIt = vec.begin();vecIt != vec.end();vecIt++)
{
hs.insert(*vecIt);
}
cout<<"hash set test :"<<endl;
for (hash_setInterator = hs.begin() ; hash_setInterator != hs.end();hash_setInterator++)
{
cout<< *hash_setInterator << " ";
}
system("pause");
return 0 ;
}
代码输出如下:
要解决中兴的笔试题,可以采用以下思路:
#include <iostream>
#include <vector>
using namespace std ;
int main()
{
int arr[] = {1,2,20,1,1,2,2,3,4,5,6,7,8,8,8,9,2,3,4,7,7,8,6,1} ;
int arrLength = sizeof(arr)/sizeof(arr[0]);
int index = 1 ;
bool isExit = false;
for(int i = 0 ; i < arrLength ; i++)
{
for (int j = 0 ; j < index ;j++ )
{
if(arr[i] == arr[j])
{
isExit = true ;
}
}
if (!isExit)
{
arr[index]= arr[i];
index++;
}
isExit = false ;
}
for (int i = 0 ;i < index ;i++)
{
cout<<arr[i]<<" ";
}
system("pause");
return 0 ;
}
输出为: