题解 | #提取不重复的整数#

提取不重复的整数

https://www.nowcoder.com/practice/253986e66d114d378ae8de2e6c4577c1

解题思路

  1. 将整数从右到左读取
  2. 使用集合(Set)来记录已经出现过的数字
  3. 逐位检查数字:
    • 如果数字未出现过,则添加到结果中
    • 如果数字已出现过,则跳过
  4. 最后输出结果

代码

#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为整数的位数
  • 空间复杂度: - 只需常数级空间存储结果和集合
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-05 04:14
已编辑
真烦好烦真烦:看着感觉好强啊,这都过不了吗
投递字节跳动等公司7个岗位 面试中的破防瞬间
点赞 评论 收藏
分享
你背过凌晨4点的八股文么:简历挂了的话会是流程终止,像我一样
点赞 评论 收藏
分享
今年读完研的我无房无车无对象,月入还没有过万&nbsp;看到他在朋友圈晒房产证,感叹自己白读了这么多年书
小浪_Coding:学历不代表就能赚多少钱, 自己硕士学历怎么说也是一方面好事, 工作只是为了谋生, 赚钱跟学历不挂钩, 看自己走什么样的路,做什么选择
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务