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

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

    The clue is you're looking for log(n). That's less than n.

    Stepping through the entire array, one at a time? That's n. That's not going to work.

    We know the first two indexes in the array (0 and 1) should be the same number. Same with 50 and 51, if the odd number in the array is after them.

    So find the middle element in the array, compare it to the element right after it. If the change in numbers happens on the wrong index, we know the odd number in the array is before it; otherwise, it's after. With one set of comparisons, we figure out which half of the array the target is in.

    Keep going from there.

提交回复
热议问题