Puzzle : finding out repeated element in an Array

后端 未结 9 1055
面向向阳花
面向向阳花 2021-02-10 17:39

Size of an array is n.All elements in the array are distinct in the range of [0 , n-1] except two elements.Find out repeated element without using extra temporary array with con

9条回答
  •  北恋
    北恋 (楼主)
    2021-02-10 17:59

    The best I can do is O(n log n) in time and O(1) in space:

    The basic idea is to perform a binary search of the values 0 through n-1, passing over the whole array of n elements at each step.

    1. Initially, let i=0, j=n-1 and k=(i+j)/2.
    2. On each run through the array, sum the elements whose values are in the range i to k, and count the number of elements in this range.
    3. If the sum is equal to (k-i)*(k-i+1)/2 + i*(k-i+1), then the range i through k has neither the duplicate nor the omitted value. If the count of elements is less than k-i+1, then the range has the omitted value but not the duplicate. In either case, replace i by k+1 and k by the new value of (i+j)/2.
    4. Else, replace j by k and k by the new value of (i+j)/2.
    5. If i!=j, goto 2.

    The algorithm terminates with i==j and both equal to the duplicate element.

    (Note: I edited this to simplify it. The old version could have found either the duplicate or the omitted element, and had to use Vlad's difference trick to find the duplicate if the initial search turned up the omitted value instead.)

提交回复
热议问题