题目描述
明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作。
我的思路与解答:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
vector<int> inputArry(n);
for(int i=0;i<n;++i)
{
cin>>inputArry[i];
}
sort(inputArry.begin(),inputArry.end());
vector<int>::iterator pos;
pos=unique(inputArry.begin(),inputArry.end());
inputArry.erase(pos,inputArry.end());
vector<int>::iterator it;
for(it=inputArry.begin();it!=inputArry.end();++it)
{
cout<<*it<<'n';
}
}
return 0;
}
主要需要注意的有:
1.vector<int> inputArry(n);
如果下面采用遍历的方式进行赋值,一定记得定义数组的时候要给定数组大小;如果采用push_back()来初始化,则不需要;
2.对sort,unique的使用,包含头文件algorithm,unique是将重复的字符放在最后,并且返回第一个重复的字符的位置;可以使用erase将这个位置到末尾的字符全部删除;
在牛客上看到一个牛人写的答案,感觉思路的确很厉害,引用一下。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main() {
int N, n;
while (cin >> N) {
int a[1001] = { 0 };
while (N--) {
cin >> n;
a[n] = 1;
}
for (int i = 0; i < 1001; i++)
if (a[i])
cout << i << endl;
}
return 0;
}
最后
以上就是过时眼神最近收集整理的关于[编程题]随机数的去重与排序的全部内容,更多相关[编程题]随机数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复