Algorithm to find two repeated numbers in an array, without sorting

前端 未结 24 2112
南方客
南方客 2020-11-28 06:58

There is an array of size n (numbers are between 0 and n - 3) and only 2 numbers are repeated. Elements are placed randomly in the array.

E.g. in {2, 3, 6, 1, 5, 4

24条回答
  •  庸人自扰
    2020-11-28 07:13

    suppose array is
    
    a[0], a[1], a[2] ..... a[n-1]
    
    sumA = a[0] + a[1] +....+a[n-1]
    sumASquare = a[0]*a[0] + a[1]*a[1] + a[2]*a[2] + .... + a[n]*a[n]
    
    sumFirstN = (N*(N+1))/2 where N=n-3 so
    sumFirstN = (n-3)(n-2)/2
    
    similarly
    
    sumFirstNSquare = N*(N+1)*(2*N+1)/6 = (n-3)(n-2)(2n-5)/6
    
    Suppose repeated elements are = X and Y
    
    so X + Y = sumA - sumFirstN;
    X*X + Y*Y = sumASquare - sumFirstNSquare;
    
    So on solving this quadratic we can get value of X and Y.
    Time Complexity = O(n)
    space complexity = O(1)
    

提交回复
热议问题