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

后端 未结 7 2024
死守一世寂寞
死守一世寂寞 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:42

    Are your ranges non-overlapping? If so you could use a TreeMap:

    TreeMap m = new TreeMap();
    m.put(1.0, 'A');
    m.put(2.9, null);
    m.put(4.0, 'B');
    m.put(6.0, null);
    m.put(6.5, 'C');
    m.put(10.0, null);
    

    The lookup logic is a bit complicated by the fact that you probably want an inclusive lookup (i.e. 2.9 maps to 'A', and not undefined):

    private static  V mappedValue(TreeMap map, K key) {
        Entry e = map.floorEntry(key);
        if (e != null && e.getValue() == null) {
            e = map.lowerEntry(key);
        }
        return e == null ? null : e.getValue();
    }
    

    Example:

    mappedValue(m, 5) == 'B'
    

    More results include:

    0.9 null
    1.0 A
    1.1 A
    2.8 A
    2.9 A
    3.0 null
    6.4 null
    6.5 C
    6.6 C
    9.9 C
    10.0 C
    10.1 null
    

提交回复
热议问题