题解 | #明明的随机数#
明明的随机数
https://www.nowcoder.com/practice/3245215fffb84b7b81285493eae92ff0
解题思路
- 首先读取输入的整数个数
- 使用集合(Set)来自动去重,C++使用
set
,Java使用TreeSet
,Python使用set
- Java的
TreeSet
自动排序,而C++的set
也是有序的,Python 需要额外排序 - 按顺序输出结果
代码
#include <iostream>
#include <set>
using namespace std;
int main() {
int n;
cin >> n;
set<int> numbers;
// 读取输入并去重
for(int i = 0; i < n; i++) {
int num;
cin >> num;
numbers.insert(num);
}
// 输出排序后的结果
for(auto num : numbers) {
cout << num << endl;
}
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// 使用TreeSet自动排序和去重
TreeSet<Integer> numbers = new TreeSet<>();
// 读取输入并去重
for(int i = 0; i < n; i++) {
numbers.add(sc.nextInt());
}
// 输出结果
for(int num : numbers) {
System.out.println(num);
}
}
}
n = int(input())
numbers = set()
# 读取输入并去重
for _ in range(n):
numbers.add(int(input()))
# 排序并输出
for num in sorted(numbers):
print(num)
算法及复杂度
- 算法:使用集合数据结构实现去重,然后排序输出
- 时间复杂度:
- 主要来自排序操作
- 空间复杂度:
- 需要存储不重复的数字