question: public List < Interval > merge ( List < Interval > intervals ) { List < Interval > res = new ArrayList < > ( ) ; if ( intervals == null || intervals . size ( ) == 0 ) { return res ; } Collections . sort ( intervals , null ) ; Interval prev = null ; for ( Interval i : intervals ) { if ( prev == null || prev . end < i . start ) { res . add ( i ) ; prev = i ; } else if ( i . end > prev . end ) { prev . end = i . end ; } } return res ; }
target:  Sort and merge, O(nlogn) time. Sort the intervals according to the start value in asc order. For each of the intervals, 1) add to result directly if the result list is empty. 2) add to result directly if there is no overlap between current interval and previous interval. 3) If there is overlap, we already know current interval's start is larger than previous interval. We need to update the end of previous interval if current interval's end is larger.