AcWing 425. 随机数 425
原题链接
简单
作者:
刘青春
,
2020-10-04 14:57:18
,
所有人可见
,
阅读 439
#include<algorithm>
#include<iostream>//Header file needed to use unique
using namespace std;
int n;
int main(){
cin>>n;
vector<int> res;
while(n--){
int a;
cin>>a;
res.push_back(a);
}
sort(res.begin(),res.end());
vector<int>::iterator it = unique(res.begin(),res.end());
res.erase(it,res.end());
cout<<res.size()<<endl;
for(auto t:res)cout<<t<<' ';
puts("");
}
改进前
#include<algorithm>
#include<iostream>
using namespace std;
const int N = 1010;
bool flag[N];
int n;
int main(){
cin>>n;
vector<int> res;
while(n--){
int a;
cin>>a;
if(!flag[a]){
res.push_back(a);
flag[a]=true;
}
}
sort(res.begin(),res.end());
cout<<res.size()<<endl;
for(auto t:res)cout<<t<<' ';
puts("");
}
生成随机数 非题解
#include<iostream>
#include<ctime>//Header file needed to use time
#include<cstdlib>//Header file needed to use srand,rand
#include<vector>//Header file needed to use vector
#include<algorithm>//Header file needed to use sort
using namespace std;
const int N = 1010;
int n;
int maxValue=100;
int minValue=1;
int flag[N];
int main(){
cin>>n;
cout<<n<<endl;
vector<int> res;
unsigned send=time(0);
srand(send);
for(int i =0;i<n;i++){
int rom = rand()%(maxValue-minValue+1)+minValue;
//res.push_back(rom);
if(!flag[rom]){
res.push_back(rom);
flag[rom]=true;
}else{
i--;
}
}
sort(res.begin(),res.end());
for(auto t:res)cout<<t<<' ';
puts("");
}