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<int[]> tm来保存每段Interval的start 和 Interval本身的对应关系.
新值进来就看能不能连上已有的Interval.
Note:
1. If val is in tm, return.
2. If val is within lower key corresponding interval, return.
Time Complexity: addNum, O(logn). getIntervals, O(n).
Space: O(n).
AC Java:
1 class SummaryRanges { 2 TreeMap<Integer, int[]> tm; 3 4 public SummaryRanges() { 5 tm = new TreeMap<>(); 6 } 7 8 public void addNum(int val) { 9 if(tm.containsKey(val)){ 10 return; 11 } 12 13 Integer l = tm.lowerKey(val); 14 Integer r = tm.higherKey(val); 15 if(l != null && r != null && tm.get(l)[1] + 1 == val && val + 1 == r){ 16 tm.get(l)[1] = tm.get(r)[1]; 17 tm.remove(r); 18 }else if(l != null && tm.get(l)[1] + 1 >= val){ 19 tm.get(l)[1] = Math.max(tm.get(l)[1], val); 20 }else if(r != null && val + 1 == r){ 21 tm.put(val, new int[]{val, tm.get(r)[1]}); 22 tm.remove(r); 23 }else{ 24 tm.put(val, new int[]{val, val}); 25 } 26 } 27 28 public int[][] getIntervals() { 29 return tm.values().toArray(new int[0][0]); 30 } 31 } 32 33 /** 34 * Your SummaryRanges object will be instantiated and called as such: 35 * SummaryRanges obj = new SummaryRanges(); 36 * obj.addNum(val); 37 * int[][] param_2 = obj.getIntervals(); 38 */