Java solution of Data stream as Disjoint Intervals


  • 0
    Y

    Thanks @qianzhige's post, learned how to use tree map, below is my version of Java code:

    public class SummaryRanges {
        private TreeMap<Integer, Interval> treeMap;
        /** Initialize your data structure here. */
        public SummaryRanges() {
            treeMap = new TreeMap<>();
        }
    
        public void addNum(int val) {
            if (treeMap.containsKey(val)) {
                return;
            }
            Integer l = treeMap.lowerKey(val);
            Integer h = treeMap.higherKey(val);
            int start = val, end = val;
            if (l != null && treeMap.get(l).end + 1 >= val) {
                start = Math.min(start, l);
                end = Math.max(end, treeMap.get(l).end);
                treeMap.remove(l);
            }
            if (h != null && treeMap.get(h).start - 1 <= val) {
                start = Math.min(start, h);
                end = Math.max(end, treeMap.get(h).end);
                treeMap.remove(h);
            }
            treeMap.put(start, new Interval(start, end));
        }
        public List<Interval> getIntervals() {
            return new ArrayList<>(treeMap.values());
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.