Finding the closest value to n, without going over, in a sorted array

空扰寡人 提交于 2019-12-25 05:36:08

问题


For this problem I have a sorted Array of doubles. I need to be able to quickly and efficiently find index of the value that is closest to, but not over, n. Efficiency is key, the assignment states is can be done in O(log n) so I assume it can be done with some sort of modified binary search.

I know this has been asked before but all answers I found either assumed an unsorted array or simply looped through the entire array comparing differences.

Any guidance is appreciated. Thank you.


回答1:


Yes, you can do it with a modified binary search; just look for the number as usual and;

  • If you find it, it's the correct number (close, but not over)
  • If you don't find it, if the last number you check is under, that's your number (you've already looked at the number above once and found it to be too high)
  • If you find it and the last number you check is over, I think you get how to find the highest one under.

Just remember that there are some error conditions to consider too and you'll do fine :)



来源:https://stackoverflow.com/questions/9523310/finding-the-closest-value-to-n-without-going-over-in-a-sorted-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!