【简单】面试题03. 数组中重复的数字

本文探讨了在LeetCode上的一道经典问题:如何在数组中找到重复的数字。提供了四种解决方案,包括使用集合、映射、排序和哈希法。每种方法都有其独特之处,适用于不同的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】
找出数组中重复的数字。在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
来源:leetcode
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
【示例1】
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
【限制】
2 <= n <= 100000
【代码】
【set】

class Solution {
public:
    set<int> s;
    int findRepeatNumber(vector<int>& nums) {
        for(auto x:nums)
            if(s.count(x))
                return x;
            else
                s.insert(x);
        return -1;
    }
};

【map】

class Solution {
public:
    map<int,int> m;
    int findRepeatNumber(vector<int>& nums) {
        for(auto x:nums)
            m[x]++;
        for(auto x:m)
            if(x.second>1)
                return x.first;
        return -1;
    }
};

【排序】

class Solution {
public:
    int pre=-1;
    int findRepeatNumber(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        for(auto x:nums){
            if(pre==x)
                return x;
            pre=x;
        }
        return -1;
    }
};

【哈希法 时间换空间】

class Solution {
public:
    int hashnum[100000]={0};
    int findRepeatNumber(vector<int>& nums) {
        for(auto x:nums){
            if(hashnum[x])
                return x;
            hashnum[x]++;
        }
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值