版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Little_Small_Joze/article/details/78623326
明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤100),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作。
有2行,第1行为1个正整数,表示所生成的随机数的N个数:
第2行有N个用空格隔开的正整数,为所产生的随机数
第1行为1个正整数M,表示不相同的随机数的个数。第2行为M个用空格隔开的正整数,为从小到大排好序的不相同的随机数。
样例输入:
10
20 40 32 67 40 20 89 300 400 15
样例输出:
8
15 20 32 40 67 89 300 400
题解一:桶排序(摘自codevs题解)
#include <iostream>
using namespace std;
int main()
{
int n,a[1001]={0},s=0;
cin>>n;
for(int i=0;i<n;i++){
int k;
cin>>k;
if(!a[k])s++;
a[k]++;
}
cout<<s<<endl;
for(int i=1;i<=1000;i++){
if(a[i])cout<<i<<" ";
}
return 0;
}
题解二:空间优化(双向链表)(笔者原创)
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
node *befr;
};
int main()
{
int n;
node *p=new node,*head,*q;
cin>>n;
if(n>0)
{
cin>>p->data;
p->next=NULL;
p->befr=NULL;
head=p;
if(n>1)
{
for(int i=1;i<n;++i)
{
node *q=new node;
cin>>q->data;
node *k=head;
while(k->data < q->data && k->next!=NULL) k=k->next;
if(k->data==q->data)
{
delete q;
continue;
}else if(k->next==NULL&&k->data < q->data)
{
k->next=q;
q->next=NULL;
q->befr=k;
continue;
}else
{
if(k->befr!=NULL)
{
k->befr->next=q;
q->next=k;
q->befr=k->befr;
k->befr=q;
}else
{
q->befr=NULL;
q->next=k;
k->befr=q;
head=q;
}
}
}
}
node *t;
t=head;
int ans=1;
while(t->next != NULL)
{
++ans;
t=t->next;
}
cout<<ans<<endl;
t=head;
while(t->next!=NULL)
{
cout<<t->data<<' ';
t=t->next;
}
cout<<t->data;
t=head;
p=head;
while(t->next!=NULL)
{
p=t;
t=t->next;
delete p;
}
delete t;
}else cout<<0;
return 0;
}
题目详情见codevs.cn1075明明的随机数