public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        List<Interval> result = new ArrayList<>();
        boolean alreadyAdded = false;
        for (int i = 0; i < intervals.size(); i++) {
            if ((intervals.get(i).end < newInterval.start)) {
                result.add(intervals.get(i));
            } else if (intervals.get(i).start > newInterval.end) {
                if (!alreadyAdded) {
                    result.add(newInterval);
                    alreadyAdded = true;
                }
                result.add(intervals.get(i));
            } else {
                newInterval.start = Math.min(newInterval.start, intervals.get(i).start);
                newInterval.end = Math.max(newInterval.end, intervals.get(i).end);
                if (!alreadyAdded) {
                    result.add(newInterval);
                    alreadyAdded = true;
                }
            }
        }
        if (!alreadyAdded) {
            result.add(newInterval);
        }
        return result;
    }
Date 03/21/2016
@author Tushar Roy

Insert internal into sorted intervals and merge them.

Time complexity O(n)

https://leetcode.com/problems/insert-interval/
src/com/interview/misc/InsertInterval.java