[Leetcode/lintcode solution to a problem] search reduplicative to count · Find The Duplicate Number

[The title is described] give out an array Nums includes N + 1 integral, every integer is from 1 include attrib border) to N (, assure to be put in integer of a reduplicative at least. Have integer of a reduplicative only suppose, find out this reduplicative number.

Online evaluate an address:Https://www.lintcode.com/problem/find-the-duplicate-number/ ? Utm_source=sc-v2ex-fks0526

[Sample] sample 1:

 Shu  Ru :
 Shu  Chu :

Sample 2:

 Shu  Ru :
 Shu  Chu :

[Solution to a problem] the method that uses the speed index that 9 chapters of & of class of 9 chapters algorithm had told in algorithmic aggrandizement class.

Should do this to inscribe you to need to do Linked List Cycle above all this problem.

If data regard as a LinkedList, I locally the value represents I the word that what the next point of the dot is, we can draw from 0 set out, altogether has N + 1 the Linked List of the dot.

A thing that can prove is, this Linked List is put in annulus certainly. Because do not have the amount of the amount that empty Next is not in the Linked List of annulus and node,the relation is poor (node is much, blame empty Next is little)

So, we proved this is watch of a catenary that take ring. And the reduplicative number that we should seek, namely two the dot was pointed to same the dot serves as Next that is nodded. Namely the entrance of annulus.

The method that because this is over,Linked List Cycle of complete apply mechanically inscribes speed finger this can.

What is speed finger algorithm?

Set out from start, slow hand make a move, fast index takes two steps. Because have link, so regular meeting encounters.

After encountering, among them a finger pullbacks start, go afresh, this speed finger each make a move. They still can encounter again, and encounter bit of entrance that is annulus.

Time is complex how much is spending?

Time is complex spend be O(n) O(n) .

public class Solution {
     * @param nums an array containing n + 1 integers which is between 1 and n
     * @return the duplicate one
    public int findDuplicate(int[] nums) {
        if (nums.length <= 1)
            return -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;

[Is method of more solution to a problem referenced] Https://www.jiuzhang.com/solution/find-the-duplicate-number/ ? Utm_source=sc-v2ex-fks0526

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *