Straightforward solution


  • 0
    G

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

        List<Interval> result = new ArrayList<>();
        int k=0;
        
        while(k<intervals.size() && isBefore(intervals.get(k), newInterval)){
                result.add(intervals.get(k++));
        }
        while(k < intervals.size() && !isBefore(newInterval, intervals.get(k)) && !isAfter(newInterval, intervals.get(k))){
            newInterval.start = Math.min(newInterval.start, intervals.get(k).start);
            newInterval.end = Math.max(newInterval.end, intervals.get(k++).end);
        }
        result.add(newInterval);
        
        while(k<intervals.size()){
            result.add(intervals.get(k++));
        }
        return result;
    }
    
    
    private boolean isBefore(Interval i1, Interval i2){
    
        if(i1.start < i2.start && i1.end < i2.start) return true;
        return false;
    }
    
    private boolean isAfter(Interval i1, Interval i2){
        
        if(i2.start < i1.start && i2.end < i1.start) return true;
        return false;
    }
    

    }
    '''


Log in to reply
 

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