Almost the same as Insert Interval


  • 0
    Z
    public class SummaryRanges {
        
        private List<Interval> l; 
        /** Initialize your data structure here. */
        public SummaryRanges() {
            l = new ArrayList<Interval>();
        }
        
        public void addNum(int val) {
            l = insert(l,new Interval(val,val));
        }
        
        public List<Interval> getIntervals() {
            return l;
        }
        
        private List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> res = new ArrayList<Interval>();
            for(Interval in: intervals) {
                if(newInterval.end < in.start - 1) {
                    res.add(newInterval);
                    newInterval = in;
                }else if(newInterval.start > in.end +1) {
                    res.add(in);
                }else {
                    newInterval = new Interval(Math.min(newInterval.start,in.start),Math.max(newInterval.end,in.end) );
                }
            }
            res.add(newInterval);
            return res;
        }
    }

Log in to reply
 

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