Find the nearest number in a list of numbers
source link: https://www.codesd.com/item/find-the-nearest-number-in-a-list-of-numbers.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Find the nearest number in a list of numbers
I have a list of constant numbers. I need to find the closest number to x in the list of the numbers. Any ideas on how to implement this algorithm?
Well, you cannot do this faster than O(N)
because you have to check all numbers to be sure you have the closest one. That said, why not use a simple variation on finding the minimum, looking for the one with the minimum absolute difference with x?
If you can say the list is ordered from the beginning (and it allows random-access, like an array), then a better approach is to use a binary search. When you end the search at index i (without finding x), just pick the best out of that element and its neighbors.
Related Articles
How to find the maximum number in a list with numbers and strings in Python?
C # Find the nearest number in Array
Find the nearest number of the given numbers in a list ~ Python
Find the largest number of selected list items in Python
Beginning of Java: Find the largest number in a list
C Function to find the nearest number in a file
how to write a function to find the maximum number in a list of type number in ocaml?
How can I find the duplicate number in a list provided and print this number?
Find the nearest number as the factors give a list of premiums
Java: find the largest number in a list of a number of integers that the user has configured
How to find the index number in a list of lists
How do you find the maximum number in a list without using the & ldquo; Max?
You are looking for an efficient algorithm to find the nearest integer in a list of integers
Find the nearest number when one of the fields is null but you need a value
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK