由键盘输入n个整数,统计不同数字的个数(0<=n<=200000)。
输入格式
第一行一个整数n(0<=n<=200000)。
第二行n个整数a1,a2…an,(0<=ai<=200000)。
输出格式
仅一行,不同数字的个数。
输入样例
20
70 5 14 22 19 2 99 67 13 66 5 93 44 38 22 11 39 22 33 11
输出样例
16
#include <iostream>
using namespace std;
int main()
{
int book[200001] = {0}; //一定要把数组中的元素定义初始值全为0
int n;
scanf("%d",&n);
int a;
for(int i = 0;i < n;i++){
scanf("%d",&a);
book[a] = 1; //用数组计数,出现过的数(对应数组下标数)为1(相同的数只会记录一次),没出现的为0
}
int c = 0;
for(int j = 0;j <= 200000;j++){
if(book[j] == 1){
c++; //统计出现数字的个数
}
}
printf("%d",c);
return 0;
}
AC代码2:利用vector的函数
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
int n;
vector<int> a;
int main()
{
ios::sync_with_stdio(false);
cin >> n;
int t;
for(int i = 0;i < n;i++){
cin >> t;
a.push_back(t);
}
sort(a.begin(),a.end());
vector<int>::iterator new_begin;//定义向量迭代器
vector<int>::iterator new_end = a.end();//定义向量迭代器
new_begin = unique(a.begin(),a.end());//提取重复元素后移到容器最后
a.erase(new_begin,new_end);//删除元素
cout << a.size() << endl;
return 0;
}
PS:
vector是声明向量容器;
例如 verctor v,就是创建了一个名字叫v的向量容器。
vector::iterator是定义向量迭代器
例如,vector::iterator it 就是定义了一个名字叫it 的向量迭代器
for(it=v.begin();it!=v.end();it++)
cout<<*it<<endl;
就把vector 向量类型的向量V中的int数据都输出了