352. Data Stream as Disjoint Intervals - jiejackyzhang/leetcode-note GitHub Wiki

Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.

For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:

[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]

Follow up: What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?

解题思路为采用TreeMap,key为每个interval的start值。 通过TreeMap可以很容易的找到lower和higher key,即没当加入一个新值时,我们可以很容易找到它的前一个和后一个interval,然后merge them if necessary。

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class SummaryRanges {
    
    TreeMap<Integer, Interval> tree;

    /** Initialize your data structure here. */
    public SummaryRanges() {
        tree = new TreeMap<>();
    }
    
    public void addNum(int val) {
        if(tree.containsKey(val)) return;
        Integer low = tree.lowerKey(val);
        Integer high = tree.higherKey(val);
        if(low != null && high != null && val == tree.get(low).end + 1 && val == high - 1) {
            tree.get(low).end = tree.get(high).end;
            tree.remove(high);
        } else if(low != null && tree.get(low).end + 1 >= val) {
            tree.get(low).end = Math.max(tree.get(low).end, val);
        } else if(high != null && val == high - 1) {
            tree.put(val, new Interval(val, tree.get(high).end));
            tree.remove(high);
        } else {
            tree.put(val, new Interval(val, val));
        }
    }
    
    public List<Interval> getIntervals() {
        return new ArrayList<>(tree.values());
    }
}

/**
 * Your SummaryRanges object will be instantiated and called as such:
 * SummaryRanges obj = new SummaryRanges();
 * obj.addNum(val);
 * List<Interval> param_2 = obj.getIntervals();
 */
⚠️ **GitHub.com Fallback** ⚠️