Find closest index by difference with BinarySearch

前端 未结 2 762
南笙
南笙 2021-02-20 18:14

I have a sorted array of about 500,000 ints. Currently I am selecting the correct index by taking the differences between my target int, and all of the elements, and then sortin

2条回答
  •  感情败类
    2021-02-20 18:47

    Just do the binary search, and if the result is negative you then find where it would be inserted and look at the next and previous entry - in other words, with your current code, check index and index - 1 (after checking that index isn't 0 :). Find out which is closer, and you're done.

提交回复
热议问题