LeetCode 287. Find the Duplicate Number

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than O(n2).
- There is only one duplicate number in the array, but it could be repeated more than once.

题意:给定一个包含n + 1个整数(其中每个整数介于1和n(含)之间)的数组nums,证明至少存在一个重复数。 假设只有一个重复数,找到重复数。
注意:

  • 不能修改队列
  • 固定O(1)额外空间
  • 时间复杂度少于O(n^2)
  • 只有一个重复数,但可能出现不止一次

    Approach One: Sort

int findDuplicate(vector<int>& nums) {
    std::sort(nums.begin(), nums.end());
    for(int i = 1; i < nums.size(); ++i)
        if(nums[i - 1] == nums[i])
            return nums[i];
    return -1;
}

Approach Two: Use Set

int findDuplicate(vector<int>& nums) {
    unordered_set<int> set;
    for(int i = 0; i < nums.size(); ++i)
        if(set.count(nums[i]) == 0)
            set.emplace(nums[i]);
        else
            return nums[i];
    return -1;
}

Approach There: Cycle Detection
我们可以把整个数组看成一个链表,寻找环,可以参考Linked List Cycle II:
https://blog.csdn.net/spade_/article/details/79593290

int findDuplicate(vector<int>& nums) {
    int slow = nums[0], fast = nums[0];
    do{
        slow = nums[slow];
        fast = nums[nums[fast]];
    }while(slow != fast);

    slow = nums[0];
    while(slow != fast){
        slow = nums[slow];
        fast = nums[fast];
    }
    return slow;
}

Approach Four: Bit Manipulation

/* 
    看了讨论,发现了Bit Manipulation的解决方法:
    对于 int 32 位,统计nums[0..n-1]在第k位的1的总数b,与0..n-1在第k位的1的总数a
    如果b > a,说明第k位存在重复(多了1)
*/
int findDuplicate(vector<int>& nums) {
    int res = 0;
    for(int k = 0; k < 32; ++k){
        int bit = (1 << k);     // 1 右移 k 位
        int a = 0, b = 0;
        for(int i = 0; i < nums.size(); ++i){
            if((i & bit) > 0) ++a;
            if((nums[i] & bit) > 0) ++b;
        }
        if(b > a) res += bit;   // 重复数的k位
    }
    return res;
}
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值