352. Data Stream as Disjoint Intervals

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?

Solution:TreeMap

思路: 不能用bucket形式保存,因为范围未知,所以只能用直接保存值的形式。为了to easily find the lower and higher keys( for merge purpose)( key is the start of the interval),所以利用TreeMap。具体通过higherKey, lowerKey API
Time Complexity: addNum: O(1) getIntervals: O(logN)
Space Complexity: O(N)

Solution Code:

/**
 * 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; }
 * }
 */
class SummaryRanges {
    TreeMap tree;

    public SummaryRanges() {
        tree = new TreeMap<>();
    }

    public void addNum(int val) {
        if(tree.containsKey(val)) return;
        Integer l = tree.lowerKey(val);
        Integer h = tree.higherKey(val);
        
        if(l != null && h != null && tree.get(l).end + 1 == val && h == val + 1) {
            // merge with low and high
            tree.get(l).end = tree.get(h).end;
            tree.remove(h);
        } else if(l != null && tree.get(l).end + 1 == val) {
            // merge with low
            tree.get(l).end = val;
        } else if(h != null && h == val + 1) {
            // merge with high
            tree.put(val, new Interval(val, tree.get(h).end));
            tree.remove(h);
        } else if(l != null && tree.get(l).end + 1 > val) {
            // already covered, then do nothing
            ;
        }
        else {
            // insert new
            tree.put(val, new Interval(val, val));
        }
    }

    public List getIntervals() {
        return new ArrayList<>(tree.values());
    }
}

你可能感兴趣的:(352. Data Stream as Disjoint Intervals)