明明的随机数题解

明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N11000之间的随机整数(N100),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作。

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明明的随机数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值