2
TreeMap<Integer, Integer> map;8
public void addRange(int left, int right) {9
// assume the given range [left, right), we want to find [l1, r1) and [l2, r2) such that l1 is10
// the floor key of left, l2 is the floor key of right. Like this:13
// Note: l2 could be the same as l1, so they are either both null or both non-null14
Integer l1 = map.floorKey(left);15
Integer l2 = map.floorKey(right);17
// try to visualize each case, and what to do based on r118
if (l1 == null && l2 == null) {20
} else if (l1 != null && map.get(l1) >= left) {24
right, map.get(l2))); // r2 will always be greater than r1, so no need to check r126
map.put(left, Math.max(right, map.get(l2)));29
// we don't want to remove the range starts at left, so left should be exclusive.30
// but we want to remove the one starts at right, so right should be inclusive.31
map.subMap(left, false, right, true).clear();34
public boolean queryRange(int left, int right) {35
Integer l = map.floorKey(left);36
if (l != null && map.get(l) >= right) {42
public void removeRange(int left, int right) {45
left); // I used lowerKey here, since we don't care about the range starting at left, as46
// it should be removed47
Integer l2 = map.lowerKey(right); // same, we don't care about the range starting at right49
// do this first, in case l1 == l2, the later one will change r1(or r2 in this case)50
if (l2 != null && map.get(l2) > right) {51
map.put(right, map.get(l2));54
if (l1 != null && map.get(l1) > left) {58
// range that starts at left should be removed, so left is inclusive59
// range that starts at right should be kept, so right is exclusive60
map.subMap(left, true, right, false).clear();