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<Integer, Interval> 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<Interval> getIntervals() {
        return new ArrayList<>(tree.values());
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • 一道白光“哧溜”一下蹿进大殿,刺眼,原来是有人把大殿的门被打开了,耀眼的白光前面,戴着金色面具的男子猛然闯进入。一...
    稻场旧事阅读 912评论 2 6
  • 闹钟在6:06响起,在这之前12分钟,刚抬腕看了一下表。 尽管内心一如既往的挣扎,但起床没有丝毫的耽搁,厕所、洗澡...
    喜歌raki阅读 521评论 1 2
  • 一、起风了 在看到那个信息之前,亦静心里从来没有想过阿郎的生活中,除了自己还会有其他女人的痕迹。他们已经太了解彼...
    天空的小鱼阅读 548评论 0 3