题目描述 明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作。
我的思路与解答:
#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将这个位置到末尾的字符全部删除;
在牛客上看到一个牛人写的答案,感觉思路的确很厉害,引用一下。
#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; }