Leetcode 287. Find the Duplicate number (Find duplicates)

Source: Internet
Author: User
Tags repetition

Original title URL: https://leetcode.com/problems/find-the-duplicate-number/

Given an array nums containing n + 1 integers where each integer is between 1 and N (inclusive), prove that at least one D Uplicate number must exist. Assume that there are only one duplicate number, find the duplicate one.

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

Method One: Apply the pigeon cage principle to find the binary method.

Because you can place up to n different numbers in the range of 1~n, the array now has n+1 numbers, so there is at least one repetition.

For a number m in the 1~n range, the number of the array that is less than or equal to M is at least m, and when it is just M, there is no repetition between the 1~m. We separate to prove.


public class Solution {public
    int findduplicate (int[] nums) {
        int. = 1, high = nums.length-1;
        while (Low

Method Two: Cyclic chain detection method. This method I did not think out, found on the Internet, the use of technology and the circular link list detection method exactly the same.


public class Solution {public
    int findduplicate (int[] nums) {
        int slow = 0, fast = 0;
        Do {
            slow = Nums[slow];
            Fast = Nums[nums[fast]];
        } while (Nums[slow]! = Nums[fast]);
        int restart = 0;
        while (Nums[restart]! = Nums[slow]) {
            restart = Nums[restart];
            slow = Nums[slow];
        }
        return Nums[restart];
    }
}
Reference article:

http://bookshadow.com/weblog/2015/09/28/leetcode-find-duplicate-number/
https://segmentfault.com/a/1190000003817671

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.