Remove Duplicate

题目描述:
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 a1,a2,…,an (1≤ai≤1000) — 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.

题意:输入一串数字,但是要去除重复的数字,并且在相同的数字的时候要保留最右边的那个
注意点:输出格式要求有点严格,必须要留下最右边的那个重复数字
不多说直接上代码

#include <iostream>
#include <cstdio>
#include <map>
#include <cstring>using namespace std;
int main () {int n;int A[60];bool vis[60];//标记每个数字是否被删除memset(vis,1,sizeof(vis));cin >> n;for (int i = 1;i <= n;i++) cin >> A[i];for (int i = 1;i <= n;i++) for (int j = i+1;j <= n ;j++) if(A[i] == A[j])//查找相同的数字,然后将左边的数字标记为已经删除vis[i] = 0;int ans = 0;//进行循环查找有多少个没被删除的数字for(int i = 1;i <= n;i++)if(vis[i])ans++;cout << ans << "\n";bool f = 1;for (int i = 1;i <= n;i++) {if(vis[i]&&f) {//输出每个没被删除的数字cout << A[i];f = 0;}else if(vis[i]&&!f)cout << " " << A[i];}cout << "\n";return 0;
}

本文链接:https://my.lmcjl.com/post/11430.html

展开阅读全文

4 评论

留下您的评论.