3 ms Java solution, easy to understand


  • 3
    J
    public class Solution {
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        if(intervals.size() == 0){
            intervals.add(newInterval);
            return intervals;
        }
        int len = intervals.size();
        for(int index = len - 1; index >= 0; index--){
            if(intersect(newInterval, intervals.get(index))){
                newInterval.start = Math.min(newInterval.start, intervals.get(index).start);
                newInterval.end = Math.max(newInterval.end, intervals.get(index).end);
                intervals.remove(index);
            }
        }
        if(intervals.size() == 0){
            intervals.add(newInterval);
            return intervals;
        }
        for(int index = 0; index < intervals.size(); index++){
            if(newInterval.end < intervals.get(index).start){
                intervals.add(index, newInterval);
                return intervals;
            }
        }
        intervals.add(newInterval);
        return intervals;
    }
    
    public boolean intersect(Interval x, Interval y){
        return !(x.start > y.end || x.end < y.start);
    }
    

    }


Log in to reply
 

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