How to find the number contained in an array of ranges of numbers in java

I have an array of java objects.

  • Each object stores two long lines that define a range of numbers.
  • I already have a guarantee that for all objects in the range the range of numbers does not overlap.

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?

+2
source share
3 answers

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;
}
+7

Comparable, a , b, a.start > b.end. , .

, , x , k k.end >= x , k.start <= x, , k - . Else, x .

+4

( ) .

:

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.

0
source

All Articles