287. Find the Duplicate Number

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:

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

题目要求空间复杂度为O(1),也就是说不能使用Hash表算法。不能更改原序列,因此,原来交换位置的做法就行不通了。

进一步优化:面对如此有归可寻的序列,我们应当尽可能地想办法优化时间复杂度至O(nlogn)或O(n),蛮力算法的时间复杂度是O(n2)。

 

我们在区间[1, n]中搜索,首先求出中点mid,然后遍历整个数组,统计所有小于等于mid的数的个数,如果个数大于mid,则说明重复值在[mid+1, n]之间,反之,重复值应在[1, mid]之间,然后依次类推,直到区间长度变为1,此时的low就是我们要求的重复值。

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int n = nums.size();
        
        if (n < 2)
            return 0;
        int low = 1;
        int high = n - 1;
        while (low < high) {
            int mid = (low + high) / 2;
            int count = 0;
            for (int i = 0; i < n; ++i) {
                if (nums[i] <= mid)
                    count++;
            }
            if (count <= mid)
                low = mid + 1;
            else
                high = mid;
        }
        return low;
    }
};

 

以上是关于287. Find the Duplicate Number的主要内容,如果未能解决你的问题,请参考以下文章

287. Find the Duplicate Number

287. Find the Duplicate Number

287. Find the Duplicate Number

287. Find the Duplicate Number

287. Find the Duplicate Number

287. Find the Duplicate Number