面试题3:数组中重复的数字,不能修改原数组

本文介绍了一种在长度为len且值域限定在【1,len-1】的数组中寻找重复数字的方法。通过二分查找算法,在不改变原数组的情况下高效地找到重复的数字,时间复杂度达到O(nlgn),空间复杂度仅为O(1)。

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

  •  
  • #include <iostream>
    #include <vector>
    /*
        面试题3:数组中重复的数字:
        问题:   在len长、值域为【1,len-1】的数组中找到重复的那个数字,不能修改原数组
        解决:   哈希表,时间空间复杂度都是o(n)
                 二分查找,不断的查找重复的数字是在值域的前半区间内,还是在后半区间内
                 时间复杂度为o(nlgn), 空间复杂度为o(1)
    
    */
    using namespace std;
    
    // 返回[low, up]范围内是否有重复数字
    bool check_repeat(const vector<int> array_n, const int len, const int up,const int low)
    {
        int number = 0;
        for(int i = 0; i < len; i++)
        {
            if (array_n[i]>=low && array_n[i]<=up)
                number++;
        }
    
        if (up-low+1 < number) return true;
        else return false;
    }
    
    //在len长、值域为【1,len-1】的数组中找到重复的那个数字
    int getduplication(const vector<int> array_n, const int len)
    {
        if (array_n.size() == 0)
            return -1;
        for (int i = 0; i < len; i++)
            if (array_n[i] > len-1 || array_n[i] < 1) return -2;
        int up = len-1;
        int low = 0;
        while(true)
        {
            if (up == low)
                break;
            if (check_repeat(array_n, len, up, low/2+up/2))
                low = low/2+up/2;
            else
                up = low/2+up/2-1;
        }
        return up;
    }
    int main(void)
    {
    
        int len;
        cin >> len;
        vector<int> array_n(len, 0);
        for (int i = 0; i < len; i++)
            cin >> array_n[i];
    
        int duplication = getduplication(array_n, len);
        if (duplication == -1)
            cout << "输入的数组为空";
        else if (duplication == -2)
            cout << "输入的数组的值域不在【" << 1 << "," << len-1 << "】之间";
        else
            cout << duplication;
    
        return 0;
    }

     

转载于:https://www.cnblogs.com/jkn1234/p/8878176.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值