Java 7 ms solution, simple, clear


  • 0
    R
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        Collections.sort(intervals, new IntervalComparator());
        List<Interval> result = new ArrayList<>();
        int index=0;
        while(index<intervals.size() && intervals.get(index).end<newInterval.start){
            result.add(intervals.get(index));
            index++;
        }
        if(index==intervals.size()){
            result.add(newInterval);
            return result;
        }
        Interval temp = new Interval();
        temp.start = Math.min(intervals.get(index).start, newInterval.start);
        temp.end = newInterval.end;
        while(index<intervals.size() && intervals.get(index).start<=newInterval.end){
            temp.end = Math.max(intervals.get(index).end, newInterval.end);
            index++;
        }
        result.add(temp);
        for(;index<intervals.size();index++){
            result.add(intervals.get(index));
        }
        return result;
    }
    
    class IntervalComparator implements Comparator<Interval>{
        public int compare(Interval o1, Interval o2){
            return o1.start-o2.start;
        }
    }

Log in to reply
 

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