Easy Understand Java Solution Beats 88%


  • 0
    Y

    Basic idea is to merge one by one and insert to new list.

    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> res = new ArrayList<>();
            boolean added = false;
            for (Interval interval: intervals) {
                if (interval.end < newInterval.start ) {
                    res.add(interval);
                } else if (interval.start > newInterval.end) {
                    if (!added) {
                        res.add(newInterval);
                        added = true;
                    }
                    res.add(interval);
                } else {
                    newInterval.start = Math.min(newInterval.start, interval.start);
                    newInterval.end = Math.max(newInterval.end, interval.end);
                }
            }
            if (!added) res.add(newInterval);
            return res;
        }
    

Log in to reply
 

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