In place and O(nlogn) with Lambda in Java 8


  • 0
    D
    public List<Interval> merge(List<Interval> intervals) {
            intervals.sort((o1, o2)->{
    			return o1.start - o2.start;
    		});
    		for (int i=0, j = i + 1; j < intervals.size();) {
    			Interval curr = intervals.get(i);
    			Interval next = intervals.get(j);
    			if (curr.end < next.start) {
    				i = j;
    				j++;
    			} else {
    				curr.end = Math.max(curr.end, next.end);
    				intervals.remove(j);
    			}
    		}
    		return intervals;
        }
    

Log in to reply
 

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