Java easy-to-understand solution with TreeMap + Comparator


  • 0
    L
    public class SummaryRanges {
        private Map<Interval, Interval> intervals;
        
        /** Initialize your data structure here. */
        public SummaryRanges() {
            this.intervals = new TreeMap<Interval, Interval>(new Comparator<Interval>() {
                @Override
                public int compare(Interval a, Interval b) {
                    if (a.end < b.start) {
                        return -1;
                    } else if (a.start > b.end) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
        }
        
        public void addNum(int val) {
            Interval interval = new Interval(val, val);
            if (!this.intervals.containsKey(interval)) {
                Interval before = new Interval(val - 1, val - 1);
                before = this.intervals.get(before);
                if (before != null) {
                    interval.start = before.start;
                    this.intervals.remove(before);
                }
                Interval after = new Interval(val + 1, val + 1);
                after = this.intervals.get(after);
                if (after != null) {
                    interval.end = after.end;
                    this.intervals.remove(after);
                }
                this.intervals.put(interval, interval);
            }
        }
        
        public List<Interval> getIntervals() {
            return new ArrayList<Interval>(this.intervals.keySet());
        }
    }
    

Log in to reply
 

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