Amazing Java Solution


  • 0
    M
    /**
     * Definition for an interval.
     * public class Interval {
     *     int start;
     *     int end;
     *     Interval() { start = 0; end = 0; }
     *     Interval(int s, int e) { start = s; end = e; }
     * }
     */
    class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> newIntervals = new LinkedList<>();        
            boolean inserted = false;
            for (Interval interval : intervals) {
                if (newInterval.end >= interval.start && interval.end >= newInterval.start) {
                    newInterval.start = Math.min(newInterval.start, interval.start);
                    newInterval.end = Math.max(newInterval.end, interval.end);
                } else {
                    if (newInterval.end < interval.start && !inserted) {
                        inserted = true;
                        newIntervals.add(newInterval);
                    }
                    newIntervals.add(interval);
                }
            }
            
            if (!inserted) {
                newIntervals.add(newInterval);
            }
            
            return newIntervals;
        }
    }
    

Log in to reply
 

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