Simple JAVA with Explanation


  • 0
    C

    The logic is add this new one first and then go through list, see if we need any merge. Here is the code:

    public List<Interval> insert(List<Interval> intervals, Interval n) {
        if(intervals.size() == 0){
            intervals.add(n);
            return intervals; 
        }
      // 1.add frist
      int original = intervals.size();
      for(int i=0;i<original;i++)
      {
          if(intervals.get(i).start>=n.start){
              intervals.add(i,n);
              break; 
          }
      }
      if(intervals.size()==original)intervals.add(n); // haven't actually add into list 
       //2.then merge if necessary 
       List<Interval> res = new ArrayList<>();
       int start = intervals.get(0).start;
       int end = intervals.get(0).end; 
       for(int i=1;i<intervals.size();i++){
             Interval cur = intervals.get(i);
             if(cur.start<=end){
                 end = Math.max(end,cur.end);
             }else{
                 Interval temp = new Interval(start,end);
                 res.add(temp);
                 start = cur.start;
                 end = cur.end;
             }
           }
       res.add(new Interval(start,end));           // add the last interval 
       return res;
     }

Log in to reply
 

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