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.

Example 1:

Input: [1,3,4,2,2]
Output: 2

Example 2:

Input: [3,1,3,4,2]
Output: 3

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.

由於不能改變input也不能用額外O(N)空間,所以sort和hashtable都不能用。這題的數字有上下界分別是1和nums.size() - 1。利用二分搜尋法,搜描所有數字並計算小於等於當前mid的數,如果cnt小於等於當前這個mid,說明重複的數字比mid還要大,如果cnt大於當前的mid,說明重複的數比mid小。

// Binary Search
int findDuplicate(vector<int>& nums) { // time: O(nlogn); space: O(1)
    int low = 1, high = nums.size() - 1;
    while (low < high) {
        int mid = low + (high - low) / 2, cnt = 0;
        for (int num : nums)
            if (num <= mid) ++cnt;
        if (cnt <= mid) low = mid + 1;
        else high = mid;
    }
    return low;
}

有點類似cycle detection in linkedlist。

// Two pointers similar to linkedlist cycle detection
int findDuplicate(vector<int>& nums) { // time: O(n); space: O(1)
    int slow = nums[0], fast = nums[nums[0]];
    while (slow != fast) {
        slow = nums[slow];
        fast = nums[nums[fast]];
    }
    slow = 0;
    while (slow != fast) {
        slow = nums[slow];
        fast = nums[fast];
    }
    return slow;
}

Last updated

Was this helpful?