求数组里重复出现的数字

https://leetcode.com/problems/find-the-duplicate-number/?tab=Description

 

没想到的是,居然重复复用了链表环形追逐的思路。非常的巧妙。而且不需要修改数组里面的数字,不需要修改原数组。

 

https://discuss.leetcode.com/topic/25913/my-easy-understood-solution-with-o-n-time-and-o-1-space-without-modifying-the-array-with-clear-explanation/2

 

int findDuplicate3(vector<int>& nums)
{
    if (nums.size() > 1)
    {
        int slow = nums[0];
        int fast = nums[nums[0]];
        while (slow != fast)
        {
            slow = nums[slow];
            fast = nums[nums[fast]];
        }

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

 

posted @ 2017-02-26 19:31  blcblc  阅读(187)  评论(0编辑  收藏  举报