Easy Java 15ms Insert Interval


  • 0
    W

    package leet;

    import ChinaMobile.Solution;

    import java.util.ArrayList;
    import java.util.List;

    /**

    • Created by wunengbiao on 2016/11/1.
      */
      public class Solution57 {
      List<Interval> ret=new ArrayList<>();
      public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
      if(intervals.size()==0){
      ret.add(newInterval);
      return ret;
      }
      Interval index=new Interval();
      boolean findStart=false;
      boolean findEnd=false;
      for(Interval interval:intervals){
      if(findStart && findEnd){
      ret.add(interval);
      }

           if(!findStart && newInterval.start<=interval.start){
               index.start=newInterval.start;
               findStart=true;
           }
           if(!findStart && newInterval.start>=interval.start && newInterval.start<=interval.end){
               index.start=interval.start;
               findStart=true;
           }
           if(!findStart) ret.add(interval);
      
           if(findStart && !findEnd &&newInterval.end<interval.start){
               index.end=newInterval.end;
               findEnd=true;
               ret.add(index);
               if(index.start<interval.start && index.end<interval.start){
                   ret.add(interval);
               }
      
           }
           if(findStart && !findEnd &&(newInterval.end>=interval.start && newInterval.end<interval.end)){
               index.end=interval.end;
               findEnd=true;
               ret.add(index);
           }
       }
       if(!findStart){
           index.start=newInterval.start;
       }
       if(!findEnd){
           index.end=newInterval.end;
           ret.add(index);
       }
       return ret;
      

      }
      }


Log in to reply
 

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