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

后端 未结 15 2046
梦如初夏
梦如初夏 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条回答
  •  猫巷女王i
    2021-01-30 11:37

    Look at the middle element of the array. With a couple of appropriate binary searches, you can find the first and its last appearance in the array. E.g., if the middle element is 'a', you need to find i and j as shown below:

    [* * * * a a a a * * *]
             ^     ^ 
             |     |
             |     |
             i     j
    

    Is j - i an even number? You are done! Otherwise (and this is the key here), the question to ask is i an even or an odd number? Do you see what this piece of knowledge implies? Then the rest is easy.

提交回复
热议问题