287. Find the Duplicate number

Source: Internet
Author: User

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 are only one duplicate number, find the duplicate one.


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


Title: If you think of this array as a linked list, the element values in the array as the next pointer in the list node,

We can find out that this problem is the beginning of the ring in the chain list.

A proof of the start node of the ring can be seen here: [http://www.cnblogs.com/li-daphne/p/5551048.html]


Idea: Use the Fast/slow method (the step size of the slow is 2), find the "linked list" Meet the Place,

At this point fast points to the start of the "list", slow then traverse (both fast and slow have a step size of one).

When Fast/slow meets again, it is the "chain-ring" entry, which is the repeating element in the array.



classSolution { Public:    intFindduplicate (vector<int>&nums) {        if(Nums.size () >1){            intFast = nums[nums[0]]; intslow = nums[0];  while(slow!=fast) {Slow=Nums[slow]; Fast=Nums[nums[fast]]; } Fast=0;  while(Fast! =slow) {Fast=Nums[fast]; Slow=Nums[slow]; }            returnslow; }        return-1; }};

287. Find the Duplicate number

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.