原题链接在这里:
题目:
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 TreeMaptm;12 /** Initialize your data structure here. */13 public SummaryRanges() {14 tm = new TreeMap ();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 getIntervals() {37 return new ArrayList (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 param_2 = obj.getIntervals();46 */