Based on Merge Intervals, only add one line code, for java


  • 0
    R
      public class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            intervals.add(newInterval);//only add this line, the rest of codes is the same as Merge Interval
            Collections.sort(intervals,new Comparator<Interval>(){
                public int compare(Interval i1, Interval i2){
                    return i1.start - i2.start;
                }
            });
            List<Interval> res = new ArrayList<Interval>();
            Interval prev = null;
            for(Interval curr : intervals){
                if(prev == null || curr.start > prev.end){
                    res.add(curr);
                    prev = curr;
                }else if(curr.end > prev.end){
                    prev.end = curr.end;
                }
            }
            return res;
        }
        
        
    }

Log in to reply
 

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