16 ms Java Solution


  • 0
    P
    public class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            
            if(intervals==null) return null; 
            int size = intervals.size();
            int i = 0;
            for(;i<size;){
                Interval interval = intervals.get(i);
                if(newInterval.end<interval.start){
                    intervals.add(i,newInterval);
                    return intervals;
                }
                if(newInterval.start>=interval.start&&newInterval.end<=interval.end){
                    
                    return intervals;
                }
                if(newInterval.start<=interval.start&&newInterval.end>=interval.start||newInterval.end>=interval.end&&newInterval.start<=interval.end)
                {
                    newInterval.start = Math.min(interval.start,newInterval.start);
                    newInterval.end = Math.max(interval.end,newInterval.end);
                    intervals.remove(i);
                    size--;
                }else if(newInterval.start>interval.end){
                    i++;continue;
                }
            }
            if(i==size)intervals.add(i,newInterval);
            return intervals;
        }
    }

Log in to reply
 

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