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

后端 未结 15 2026
梦如初夏
梦如初夏 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:21

    Use a hash table

    For each element E in the input set
        if E is set in the hash table
             increment it's value
        else        
             set E in the hash table and initialize it to 0
    
    For each key K in hash table
        if K % 2 = 1
            return K
    

    As this algorithm is 2n it belongs to O(n)

提交回复
热议问题