I have a situation where I need to find the value with the key closest to the one I request. It’s kind of like a nearest map that defines distance between keys.
For example, if I have the keys {A, C, M, Z} in the map, a request for D would return C’s value.
Any idea?
Most tree data structures use some sort of sorting algorithm to store and find keys. Many implementations of such can locate a close key to the key you probe with (usually it either the closest below or the closest above). For example Java’s
TreeMapimplements such a data structure and you can tell it to get you the closest key below your lookup key, or the closest key above your lookup key (higherKeyandlowerKey).If you can calculate distances (its not always easy – Java’s interface only require you to know if any given key is “below” or “above” any other given key) then you can ask for both closest above and closest below and then calculate for yourself which one is closer.