LeetCode 287. Find the Duplicate Number 题解(C++)

LeetCode 287. Find the Duplicate Number 题解(C++)


题目描述

  • 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.

补充

  • 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(n^2).
  • There is only one duplicate number in the array, but it could be repeated more than once.

思路

二分法

  • 用两个指针low和high指向数字1和数字n(注意这里不是指向数组的首元素和尾元素),之后算出low和high的中间指针mid,并将mid与数组的每一个元素作比较,并记录数组中的元素小于等于mid的个数,若其个数大于mid,则表示在范围low到mid的数中有超过mid-low+1个数存在,这是可以确定重复的数字肯定在low和mid之间;否则,可以确定重复的数字在mid+1和high之间;
  • 该算法的时间复杂度为O(nlogn),空间复杂度为O(1)。

带环链表法

  • 带环链表有两个性质:
    1.假设用两个指针分别指向链表的头结点,之后一个指针以每次前进一个结点,另一个指针以每次前进两个结点(可以是多个),则两个指针肯定会在链表的环里相遇;
    2.设置一个指针从链表的头结点出发,一个指针从环里相遇的结点出发,两个指针每次都前进一个结点,则它们会在环的入口相遇;
    对带环链表的性质及推导不熟悉的请参考判断链表是否有环
  • 基于上面的性质,我们把数组元素的内容看成是下一个结点的下标,则数组可以看成是一个链表,然后我们设置一个慢指针slow(每次行进一个结点)和一个快指针fast(每次行进两个结点),当它们相遇时,再令fast指针从链表头结点(即数组首元素)出发,slow从当前的位置(即相遇的结点)出发,两者每次都行进一个结点,当它们相遇时,就可以得到链表环的入口,即重复的元素。

代码

二分法

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

带环链表法

class Solution 
{
public:
    int findDuplicate(vector<int>& nums) 
    {
        int slow = nums[0];
        int fast = nums[nums[0]];
        while (slow != fast)
        {
            slow = nums[slow];
            fast = nums[nums[fast]];
        }
        fast = 0;
        while (slow != fast)
        {
            slow = nums[slow];
            fast = nums[fast];
        }
        return slow;
    }
};

你可能感兴趣的:(LeetCode)