Concise and easy understand Java solution


  • 0
    X
    public class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> result = new ArrayList<Interval>();
            boolean flag = false;
            for (Interval interval : intervals) {
                if (interval.end < newInterval.start) {
                    result.add(interval);
                } else if (interval.start > newInterval.end) {
                    if (!flag) {
                        result.add(newInterval);
                        flag = true;
                    }
                    result.add(interval);
                } else {
                    newInterval.start = Math.min(newInterval.start, interval.start);
                    newInterval.end = Math.max(newInterval.end, interval.end);
                }
            }
            if (!flag) result.add(newInterval);
            return result;
        }
    }

Log in to reply
 

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