My intuitive solution using a boolean indicator


  • 0
    L
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        List<Interval> ret = new ArrayList<>();
        boolean inserted = false;
        
        for (Interval itv : intervals) {
            if (newInterval.start > itv.end) {
                ret.add(itv);
            } else if (newInterval.end < itv.start) {
                if (!inserted) {
                    ret.add(newInterval);
                    inserted = true;
                }
                ret.add(itv);
            } else {
                newInterval.start = Math.min(itv.start, newInterval.start);
                newInterval.end = Math.max(itv.end, newInterval.end);
            }
        }
        
        if (!inserted) {
            ret.add(newInterval);
        }
        
        return ret;
    }

Log in to reply
 

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