问题
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