题目链接:http://codeforces.com/contest/978/problem/A
A. Remove Duplicates
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Petya has an array
a
consisting of
n
integers. He wants to remove duplicate (equal) elements.
Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
Input
The first line contains a single integer
n
(
1
≤
n
≤
50
) — the number of elements in Petya’s array.
The following line contains a sequence
a
1
,
a
2
,
…
,
a
n
(
1
≤
a
i
≤
1
000
) — the Petya’s array.
Output
In the first line print integer
x
— the number of elements which will be left in Petya’s array after he removed the duplicates.
In the second line print
x
integers separated with a space — Petya’s array after he removed the duplicates. For each unique element only the rightmost entry should be left.
Examples
inputCopy
6
1 5 5 1 6 1
outputCopy
3
5 6 1
inputCopy
5
2 4 2 4 4
outputCopy
2
2 4
inputCopy
5
6 6 6 6 6
outputCopy
1
6
直接上代码,有注释:
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<sstream>
#include<map>
#include<set>
using namespace std;
set<int> s;
set<int> s1;
map<int,int> m;
int main(){
int n;
cin>>n;
int *a=new int[n];
for(int i=0;i<n;i++){
cin>>a[i];
s.insert(a[i]);//用set统计不同的数字个数
m[a[i]]=i;//更新每个点的下标 ,记录最右边的下标
}
printf("%d\n",s.size());
int first=1;
for(int i=0;i<n;i++){
if(i==m[a[i]]&&first){
printf("%d",a[i]);
first=0;
}
else if(i==m[a[i]]){
printf(" %d",a[i]);
}
}
printf("\n");
delete a;
return 0;
}