My ac java solution


  • 0
    B

    public class Solution {
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {

        List<Interval> result = new ArrayList<Interval>();
        
        int i = 0;
        //find all intervals not overlapping with new one
        while (i < intervals.size() && intervals.get(i).end < newInterval.start){
            result.add(intervals.get(i));
            i++;
        }
        
        if (i == intervals.size()){
            result.add(newInterval);
        }else{
            
            //find and merge all overlapping ones with new one, add merged one to the result
            Interval temp = newInterval;
            
            while (i < intervals.size() && intervals.get(i).start <= newInterval.end){
                temp = merge(temp, intervals.get(i));
                i++;
            }
            
            result.add(temp);
            
            //add the rest to result
            while (i < intervals.size()){
                result.add(intervals.get(i));
                i++;
            }
        }
    
        return result;
        
    }
    
    private Interval merge(Interval i1, Interval i2){
        Interval a = new Interval();
        a.start = Math.min(i1.start, i2.start);
        a.end = Math.max(i1.end, i2.end);
        return a;
    }
    

    }


Log in to reply
 

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