网易游戏2017招聘笔试题(消除重复元素)
题意:
小易有一个长度为n序列,小易想移除掉里面的重复元素,但是小易想是对于每种元素保留最后出现的那个。小易遇到了困难,希望你来帮助他。
输入描述:
输入包括两行:
第一行为序列长度n(1 ≤ n ≤ 50)
第二行为n个数sequence[i](1 ≤ sequence[i] ≤ 1000),以空格分隔
输出描述:
输出消除重复元素之后的序列,以空格分隔,行末无空格
输入例子:
9
100 100 100 99 99 99 100 100 100
输出例子:
99 100
分析:
题目的意思很简单,意思就是保留重复元素的一个元素,具体的可以看这个文章http://blog.csdn.net/fool_ran/article/details/72511341 的第三题,这里我们只需要从后向前就行,
至于剩下的空间,用0填充。输出时跳过0即可。同样使用双指针法。i=n-2,j=n-1;
if(a[i] != a[j]) a[–j] = a[i];(这里这个算法只是对应排序的数组有效),因此,我们需要考虑新的的数组。既然无序,我们可以使用map纪录当前的数字是否出现过,如果没哟就继续更新,否则就跳过。
Code:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<string>
#include<string.h>
using namespace std;
typedef long long LL;
const int MAXN = 1005;
int main()
{
int n,v;
while(cin>>n){
vector<int> a;
map<int,int> vis;
for(int i=0;i<n;i++){
cin>>v;
a.push_back(v);
}
int j=n-1;
vis[a[n-1]] = 1;
for(int i=n-1;i>=0;i--){
if(vis[a[i]] == 0){
a[--j] = a[i];
vis[a[i]] = 1;
}
}
cout<<a[j];
for(int i=j+1;i<n;i++){
cout<<" "<<a[i];
}
cout<<endl;
}
return 0;
}