LeetCode 352. Data Stream as Disjoint Intervals

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 352. Data Stream as Disjoint Intervals相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/data-stream-as-disjoint-intervals/description/

题目:

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<Integert, Interval> tm来保存每段Interval的start 和 Interval本身的对应关系. 

新值进来就看能不能连上已有的Interval.

Time Complexity: addNum, O(logn). getIntervals, O(n).

Space: O(n).

AC Java:

 1 /**
 2  * Definition for an interval.
 3  * public class Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() { start = 0; end = 0; }
 7  *     Interval(int s, int e) { start = s; end = e; }
 8  * }
 9  */
10 class SummaryRanges {
11     TreeMap<Integer, Interval> tm;
12     /** Initialize your data structure here. */
13     public SummaryRanges() {
14         tm = new TreeMap<Integer, Interval>();
15     }
16     
17     public void addNum(int val) {
18         if(tm.containsKey(val)){
19             return;
20         }
21         Integer l = tm.lowerKey(val);
22         Integer r = tm.higherKey(val);
23         if(l!=null && r!=null && tm.get(l).end+1==val && val+1==r){
24             tm.get(l).end = tm.get(r).end;
25             tm.remove(r);
26         }else if(l!=null && tm.get(l).end+1>=val){
27             tm.get(l).end = Math.max(val, tm.get(l).end);
28         }else if(r!=null && val+1==r){
29             tm.put(val, new Interval(val, tm.get(r).end));
30             tm.remove(r);
31         }else{
32             tm.put(val, new Interval(val, val));
33         }
34     }
35     
36     public List<Interval> getIntervals() {
37         return new ArrayList<Interval>(tm.values());
38     }
39 }
40 
41 /**
42  * Your SummaryRanges object will be instantiated and called as such:
43  * SummaryRanges obj = new SummaryRanges();
44  * obj.addNum(val);
45  * List<Interval> param_2 = obj.getIntervals();
46  */

 


以上是关于LeetCode 352. Data Stream as Disjoint Intervals的主要内容,如果未能解决你的问题,请参考以下文章

leetcode@ [352] Data Stream as Disjoint Intervals (Binary Search & TreeSet)

[leetcode]352. Data Stream as Disjoint Intervals

352. Data Stream as Disjoint Intervals

352. Data Stream as Disjoint Interval

352. Data Stream as Disjoint Intervals

352. Data Stream as Disjoint Intervals