Short Java solution.


  • 1
    J
    public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
         if (intervals.size() < 2)
        	return intervals;
     	List<Interval> ans = new ArrayList<>();
        Collections.sort(intervals, (a, b)->(a.start - b.start));
        int mergedStart = intervals.get(0).start; 
        int mergedEnd = intervals.get(0).end;
        for (Interval interval : intervals) {
        	if (interval.start <= mergedEnd) {
        		mergedEnd = Math.max(mergedEnd, interval.end);
        	} else {
        		ans.add(new Interval(mergedStart, mergedEnd));
        		mergedStart = interval.start;
        		mergedEnd = interval.end;
        	}
        }
        ans.add(new Interval(mergedStart, mergedEnd));
        return ans;
    }

Log in to reply
 

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