Leetcode:find the Duplicate number

Source: Internet
Author: User

Find the Duplicate number

Total Accepted: 26713 Total Submissions: 68841 Difficulty: Hard

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.

Note:

    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.

Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.

Subscribe to see which companies asked this question

Hide TagsBinary Search Array of pointersHide Similar Problems(H) First Missing Positive (m) single number (m) Linked List Cycle II (m) Missing number



























Ideas:

(1) Take a direct look at an example

Index:0 1 2 3 4 5 6 7 8

Nums:2 1 4 7 5 6 4 3 8


(2) starting from index = 0, you can see that there is a loop:

6->, 4, 2, 6, index:0, .....

Nums[index]: 2, 4, 5, 6, 4-> .....


(3) can be seen from [4->5->6->4] is a loop, exactly 4 is the duplicate number we requested.


Is it a bit like: The entry point of the Linked list Cycle II in the Find ring.



C + + code:

Class Solution {public:    int findduplicate (vector<int>& nums) {                int size = Nums.size ();                if (Size < 2) return-1;                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:find the Duplicate number

Related Article

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.