码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 352. Data Stream as Disjoint Intervals

时间:2018-02-11 12:25:51      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:ems   ini   color   and   follow   example   ted   lan   void   

原题链接在这里: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

标签:ems   ini   color   and   follow   example   ted   lan   void   

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/8440579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!