LeetCode 352. Data Stream as Disjoint Intervals

原題連接在這裏:https://leetcode.com/problems/data-stream-as-disjoint-intervals/description/html

題目:url

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

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

[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?code

題解:htm

利用TreeMap<Integert, Interval> tm來保存每段Interval的start 和 Interval自己的對應關係. blog

新值進來就看能不能連上已有的Interval.ip

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

Space: O(n).rem

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  */

 相似Missing RangesSummary Ranges.

相關文章
相關標籤/搜索