LeetCode Problem

56. Merge Intervals Link to LeetCode Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. Analysis The key to solve this problem is defining a Comparator first to sort the arraylist of Intevals. public List< Interval> merge(List intervals) { if(intervals == null || intervals.size()<=1){ return intervals; } Collections.sort(intervals, Comparator.comparing((Interval itl)->itl.start)); List result = new ArrayList<>(); Interval t = intervals.get(0); for(int i=1; i< intervals.size(); i++){ Interval c = intervals.get(i); if(c.start <= t.end){ t.end = Math.max(t.end, c.end); }else{ result.add(t); t = c; } } result.add(t); return result; }