Description
给定一个按升序排列的顺序表,请删除所有重复的元素,使得每个元素只出现一次,并输出处理后的顺序表。
Input
第一行输入t,表示有t个测试样例。
第二行起,每一行首先输入n,表示有n个元素,接着依次输入n个元素。
Output
每一行输出处理后的顺序表。
Sample
#0
Input
5 3 1 1 2 5 1 1 2 3 3 6 1 1 1 2 2 2 7 -1 22 33 33 33 44 44 0
Output
2 1 2 3 1 2 3 2 1 2 4 -1 22 33 44 0
Hint
0 <= n <= 50
-100 <= 元素的值 <= 100
给定的顺序表为升序排列。
利用了集合内元素不重复的特性,解决了去重问题。试验了vector合set的用法。
//
// Created by 86133 on 2023/10/8.
//
#include <iostream>
#include <vector>
#include <set> //包含集合头文件,主要是为了定义和使用集合numSet来完成元素去重的功能
using namespace std;
int main() {
int t;
cin >> t;
while (t--){
int n;
cin >> n;
vector<int> nums;
set<int> numSet; //定义了一个int类型元素的集合numSet
for(int j=0; j<n; j++) {
int num;
cin >> num;
nums.push_back(num);
}
for(int num : nums) {
if(numSet.count(num) == 0) { //count()函数检查元素是否在集合中,count()返回1,存在,返回0,不存在.
// 此处返回0即执行 if语句 内的代码
numSet.insert(num); //添加元素到集合numSet
}
}
cout<<numSet.size()<<" ";
for(int num : numSet){
cout<<num<<" ";
}
// 或者构造新的容器nums2,复制numSet中的元素输出
// vector<int> nums2(numSet.begin(), numSet.end());
//
// for(int num : nums2) {
// cout << num << " ";
// }
cout << endl;
}
return 0;
}