How can I find a number which occurs an odd number of times in a SORTED array in O(n) time?

后端 未结 15 2024
梦如初夏
梦如初夏 2021-01-30 10:31

I have a question and I tried to think over it again and again... but got nothing so posting the question here. Maybe I could get some view-point of others, to try and make it w

15条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 11:19

    A sorted array suggests a binary search. We have to redefine equality and comparison. Equality simple means an odd number of elements. We can do comparison by observing the index of the first or last element of the group. The first element will be an even index (0-based) before the odd group, and an odd index after the odd group. We can find the first and last elements of a group using binary search. The total cost is O((log N)²).

    PROOF OF O((log N)²)

      T(2) = 1 //to make the summation nice
      T(N) = log(N) + T(N/2) //log(N) is finding the first/last elements
    

    For some N=2^k,

    T(2^k) = (log 2^k) + T(2^(k-1))
           = (log 2^k) + (log 2^(k-1)) + T(2^(k-2))
           = (log 2^k) + (log 2^(k-1)) + (log 2^(k-2)) + ... + (log 2^2) + 1
           = k + (k-1) + (k-2) + ... + 1
           = k(k+1)/2
           = (k² + k)/2
           = (log(N)² + log(N))/ 2
           = O(log(N)²)
    

提交回复
热议问题