Find any one of multiple possible repeated integers in a list

前端 未结 6 470
一生所求
一生所求 2021-01-02 02:18

Given an array of n+1 integers, each in the range 1 to n, find an integer that is repeated.

I was asked this at a job intervi

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 02:59

    If you know that there is exactly one number that is duplicate you can find it by summing all of them and subtracting the sum of numbers from 1 to n:

    duplicate = sum P[i] - n(n+1)/2
    

    If not, then you can iterate through the array and put each number in a hashtable. If the number already exists then that's the duplicate. This is also O(n) assuming the hashtable operations are O(1).

    Or event better - to avoid the hashtable you can use an array of booleans of size n:

    int[] P = new int[] { 3, 2, 5, 1, 4, 2 };
    bool[] Q = new bool[6];
    
    foreach( var p in P ){
        if ( Q[p] ) {
            Console.WriteLine("Duplicate: " + p);
            break;
        }
        Q[p] = true;
    }
    

提交回复
热议问题