Data structures that can map a range of keys to a value

后端 未结 7 2045
死守一世寂寞
死守一世寂寞 2020-11-27 18:02

I am trying to find a data structure that takes in a particular value from a range of values and map it to a key.

For example, I have the following conditions:

7条回答
  •  星月不相逢
    2020-11-27 18:40

    This seems like a natural situation to use a tree structure.

    Unfortunately it won't be practical to implement the java.util.Map interface because it specifies a method to return all of the keys, and in your situation you theoretically have an impractically large number of keys.

    Each node of your tree should have a minimum key, a maximum key, and a value associated with that range. You can then have links to the nodes representing the next higher and next lower range (if they exist). Something like:

    public class RangeMap, V> {
        protected boolean empty;
        protected K lower, upper;
        protected V value;
        protected RangeMap left, right;
    
        public V get(K key) {
            if (empty) {
                return null;
            }
    
            if (key.compareTo(lower) < 0) {
                return left.get(key);
            }
    
            if (key.compareTo(upper) > 0) {
                return right.get(key);
            }
    
            /* if we get here it is in the range */
            return value;
        }
    
        public void put(K from, K to, V val) {
            if (empty) {
                lower = from;
                upper = to;
                value = val;
                empty = false;
                left = new RangeMap();
                right = new RangeMap();
                return;
            }
    
            if (from.compareTo(lower) < 0) {
                left.put(from, to, val);
                return;
            }
    
            if (to.compareTo(upper) > 0) {
                right.put(from, to, val);
                return;
            }
    
            /* here you'd have to put the code to deal with adding an overlapping range,
               however you want to handle that. */
        }
    
        public RangeMap() {
            empty = true;
        }
    }
    

    If you need faster lookups than the tree can provide, you may want to look into something like a skip list or developing your own hash function.

提交回复
热议问题