# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e
classSolution(object): defmerge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ res = [] for i insorted(intervals, key=lambda i: i.start): if res and i.start <= res[-1].end: res[-1].end = max(res[-1].end, i.end) else: res.append(i) return res
public List<Interval> merge(List<Interval> intervals){ if (intervals.size() <= 1) return intervals; // Sort by ascending starting point using an anonymous Comparator intervals.sort((i1, i2) -> Integer.compare(i1.start, i2.start)); List<Interval> result = new LinkedList<Interval>(); int start = intervals.get(0).start; int end = intervals.get(0).end; for (Interval interval : intervals) { if (interval.start <= end) // Overlapping intervals, move the end if needed end = Math.max(end, interval.end); else { // Disjoint intervals, add the previous one and reset bounds result.add(new Interval(start, end)); start = interval.start; end = interval.end; } } // Add the last interval result.add(new Interval(start, end)); return result; }