LeetCode : 287. Find the Duplicate Number

如果没有限制,这是一道很简单的题目。

但是有趣的是,要用O(1)的空间复杂度和小雨O(n2)的时间复杂度解决。

这里遇到了一个很有趣的算法:龟兔算法。

Adam:龟兔算法为什么有效:

http://adam8157.info/blog/2015/08/why-does-tortoise-and-hare-algorithm-work/

佛洛伊德判圈算法,也成龟兔算法(tortoise and hare

# File: FindDuplicate.py
# Author: Keith Schwarz (htiek@cs.stanford.edu)

http://keithschwarz.com/interesting/code/?dir=find-duplicate

 

Copy 一段别人的代码:

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 @ 2016-05-10 11:44  盛小胖  阅读(188)  评论(0编辑  收藏  举报