I have an array of java objects.
I want to quickly find a specific object in an array, given a number that may (or may not) fall into one of the ranges of numbers defined by the objects.
I was hoping to do this using Array.binarySearch, but that does not look appropriate.
Any thoughts on the best way to do this?
Use TreeMap. The key is the lower of the two boundaries of a long range; value is an object.
private TreeMap<Long, T> map = new TreeMap<Long, T>(); void insertObject(T object) { map.put(object, object.getLowerRangeBoundary()); } T getObjectByKeyInRange(Long query) { // Get the first Object in the tree that corresponds with the query Map.Entry<Long, T> e = map.floorEntry(query); // If there no entry, then the query value is lower than all ranges in the tree if (e == null) { return null; } T target = e.getValue(); // "target" is the only object that can contain the query value // If the query value is within the range of "target", then it is our object if (query < target.getUpperRangeBoundary()) { return target; } // Nobody has the query value in their range; return null return null; }
Comparable, a , b, a.start > b.end. , .
, , x , k k.end >= x , k.start <= x, , k - . Else, x .
( ) .
:
rangeMap TreeMap:
foreach(Range r in ranges) rangeMap[r.start].Increment(); rangeMap[r.end].Decrement();
rangeMap.GreatestLowerBound(i) , (.. GreatestLowerBound - <= i).
You can do everything possible in terms of practical performance if you know the number of ranges up ... by selecting one array, filling it with "deltaRange", then "integrating" to get an array showing the total "ranges" for each number x.