https://www.luogu.com.cn/problem/P1059
题目见链接。
题目要求对数组进行排序和去重,如果用c语言做进行排序和去重非常的麻烦,在这种情况下错误率
会比较高,因此对于这种排序去重的题目便打算用c++的STL模板来做。
利用sort函数进行排序,一行代码解决排序问题。
利用unique函数一行代码解决去重问题。
下面提供二种方法:
第一种:使用sort和unique:还有一种类似的是只是用sort函数,但去重的时候比较麻烦。
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 int a[1005]; 5 int main(){ 6 int t; 7 cin >> t; 8 for(int i = 0 ; i < t; i ++) cin >> a[i]; 9 sort( a, a + t); //先进行排序 10 int num = unique(a , a + t) - a; //去重,不要忘了减去a 11 cout << num << endl; //num即为不重复的数量 12 for(int i = 0 ; i < num ; i ++){ 13 cout << a[i] << ' ' ; //打印答案 14 } 15 return 0; 16 }
第二种:不适用STL模板,将输入的数字放入到数组的下标中。
1 #include <iostream> 2 using namespace std; 3 int a[1005]; 4 int main(){ 5 int num, index,res = 0; 6 cin >> num; 7 for(int i = 0 ; i < num; i ++){ 8 cin >> index; 9 if(a[index] == 0){ 10 a[index] = index; //将元素值输入到数组下标中,如果该位置为0 11 res++; //则代表之前未输入进去,于是输入,res加一 12 } 13 } 14 cout << res << endl; 15 for(int i = 0; i < 1005; i ++){ 16 if(a[i] != 0){ 17 cout << i <<' '; //碰到不为0的便输出,不用排序,因为在输入的时候 18 } //就已经排好了 19 } 20 return 0; 21 }