题目## 题目
解题思路
- 将整数从右到左读取
- 使用集合(Set)来记录已经出现过的数字
- 逐位检查数字:
- 如果数字未出现过,则添加到结果中
- 如果数字已出现过,则跳过
- 最后输出结果
代码
#include <iostream>
#include <set>
using namespace std;
int main() {
int n;
cin >> n;
set<int> seen;
int result = 0;
while(n > 0) {
int digit = n % 10;
if(seen.find(digit) == seen.end()) {
seen.insert(digit);
result = result * 10 + digit;
}
n /= 10;
}
cout << result << endl;
return 0;
}
import java.util.Scanner;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashSet<Integer> seen = new HashSet<>();
int result = 0;
while(n > 0) {
int digit = n % 10;
if(!seen.contains(digit)) {
seen.add(digit);
result = result * 10 + digit;
}
n /= 10;
}
System.out.println(result);
}
}
n = int(input())
seen = set()
result = 0
while n > 0:
digit = n % 10
if digit not in seen:
seen.add(digit)
result = result * 10 + digit
n //= 10
print(result)
算法及复杂度
- 算法:使用集合去重,逐位处理整数
- 时间复杂度: O ( d ) \mathcal{O}(d) O(d) - 其中d为整数的位数
- 空间复杂度: O ( 1 ) \mathcal{O}(1) O(1) - 只需常数级空间存储结果和集合
解题思路
这是一个排序问题,需要根据输入的排序标识对整数数组进行升序或降序排序。
关键点
-
输入格式:
- 第一行:数组元素个数 n n n ( 1 ≤ n ≤ 1000 1 \leq n \leq 1000 1≤n≤1000)
- 第二行: n n n个整数,空格分隔 ( 0 ≤ v a l ≤ 100000 0 \leq val \leq 100000 0≤val≤100000)
- 第三行:排序标识(0表示升序,1表示降序)
-
处理要求:
- 根据排序标识选择排序方向
- 输出排序后的数组
代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
while (cin >> n) {
// 读入数组
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
// 读入排序标识
int flag;
cin >> flag;
// 根据标识排序
if (flag == 0) {
// 升序
sort(nums.begin(), nums.end());
} else {
// 降序
sort(nums.begin(), nums.end(), greater<int>());
}
// 输出结果
for (int i = 0; i < n; i++) {
cout << nums[i] << " ";
}
cout << endl;
}
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
// 读入数组长度
int n = sc.nextInt();
// 读入数组
Integer[] nums = new Integer[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
// 读入排序标识
int flag = sc.nextInt();
// 根据标识排序
if (flag == 0) {
// 升序
Arrays.sort(nums);
} else {
// 降序
Arrays.sort(nums, Collections.reverseOrder());
}
// 输出结果
for (int num : nums) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
while True:
try:
# 读入数组长度
n = int(input())
# 读入数组
nums = list(map(int, input().split()))
# 读入排序标识
flag = int(input())
# 根据标识排序
nums.sort(reverse=(flag == 1))
# 输出结果
print(" ".join(map(str, nums)))
except:
break
算法及复杂度
算法分析
-
输入处理:
- 读取数组长度
- 读取数组元素
- 读取排序标识
-
排序过程:
- 使用标准库排序函数
- 根据标识决定升序或降序
- 输出排序后的结果
复杂度分析
- 时间复杂度: O ( n log n ) \mathcal{O}(n\log n) O(nlogn) - 使用标准排序算法
- 空间复杂度: O ( n ) \mathcal{O}(n) O(n) - 需要存储输入数组
4万+

被折叠的 条评论
为什么被折叠?



