Guessing a number knowing only if the number proposed is lower or higher?

前端 未结 7 942
悲哀的现实
悲哀的现实 2021-01-02 21:34

I need to guess a number. I can only see if the number I\'m proposing is lower or higher. Performance matters a whole lot, so I thought of the following algorithm:

Le

相关标签:
7条回答
  • 2021-01-02 22:31

    Yes, binary search (your algorithm) is correct here. However there is one thing missing in the standard binary search:

    For binary search you normally need to know the maximum and minimum between which you are searching. In case you do not know this, you have to iteratively find the maximum in the beginning, like so:

    • Start with zero
    • if it is higher than the number searched, zero is your maximum and you have to find a minimum
    • if it is lower than the number searched, zero is your minimum and you have to find a maximum
    • You can search for your maximum/minimum by starting at 1 or -1 and always multiplying by two until you find a number which is greater/smaller

    When you always multiply by two, you will be much faster than when you search linearly.

    0 讨论(0)
提交回复
热议问题