显然,Disjoint Intervals需要通过二分搜索的方式进行维护。
插入一个数n时,假设k1([k1,v1]为<=n的最大的作为intervals开始的数,k2([k2,v2])为>=n的最小的作为intervals开始的数,可能会发生四种情况:
1. v1 + 1 == n == k2 - 1,此时,需要将[k1,v1], [k2, v2]区间merge为[k1, v2]
2. v1 + 1 == n < k2 - 1,此时,需要将[k1, v1]区间变成[k1, n]
3. v1 + 1 < n == k2 - 1,此时,需要将[k2, v2]区间变成[n, v2]
4.v1 >= n 或者 k2 <= n,此时,不需要进行操作
可以直接用Java中的TreeMap数据结构来实现
class SummaryRanges {
TreeMap<Integer, Integer> tree = new TreeMap<>();
/** Initialize your data structure here. */
public SummaryRanges() {
}
public void addNum(int val) {
Integer floor = tree.floorKey(val);
Integer ceil = tree.ceilingKey(val);
if (ceil != null && ceil == val + 1 && floor != null && tree.get(floor) == val - 1){
int left = floor, right = tree.get(ceil);
tree.remove(ceil);
tree.remove(floor);
tree.put(left, right);
}
else if (ceil != null && ceil == val + 1) {
int left = val, right = tree.get(ceil);
tree.remove(ceil);
tree.put(left, right);
}
else if (floor != null && tree.get(floor) == val - 1) {
int left = floor, right = val;
tree.remove(floor);
tree.put(left, right);
}
else if ((floor != null && tree.get(floor) >= val) || (ceil != null && ceil == val))
return;
else {
int left = val, right = val;
tree.put(left, right);
}
}
public int[][] getIntervals() {
int[][] result = new int[tree.size()][2];
int i = 0;
for(Map.Entry<Integer, Integer> entry:tree.entrySet()){
result[i][0] = entry.getKey();
result[i][1] = entry.getValue();
i++;
}
return result;
}
}
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* int[][] param_2 = obj.getIntervals();
*/