题解 | #提取不重复的整数#
提取不重复的整数
https://www.nowcoder.com/practice/253986e66d114d378ae8de2e6c4577c1
解题思路
- 将整数从右到左读取
- 使用集合(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)
算法及复杂度
- 算法:使用集合去重,逐位处理整数
- 时间复杂度:
- 其中d为整数的位数
- 空间复杂度:
- 只需常数级空间存储结果和集合