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] overlaps, merge them into [1,6].
Example 2:
**Input:** intervals = [[1,4],[4,5]]
**Output:** [[1,5]]
**Explanation:** Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
ac
classSolution {publicList<Interval> merge(List<Interval> intervals) {List<Interval> res =newArrayList<Interval>();// sort listCollections.sort(intervals, (Interval i1,Interval i2) -> {returni1.start-i2.start; });// dfs handle intervalmerge(intervals,0, res);return res; }privatevoidmerge(List<Interval> intervals,int pos,List<Interval> res) {int size =intervals.size();if (pos >= size) return;int start =intervals.get(pos).start;int end =intervals.get(pos).end;for (int i = pos; i < size; i++) {if (i == size -1||intervals.get(i+1).start> end) {res.add(newInterval(start, end));merge(intervals, i+1, res);break; } end =Math.max(end,intervals.get(i+1).end); } }}
ac2:
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */classSolution {publicList<Interval> merge(List<Interval> intervals) {List<Interval> res =newArrayList<Interval>();// edge casesif (intervals ==null||intervals.size() <=1) return intervals;// sortCollections.sort(intervals, (a, b) -> {returna.start-b.start;});// iterate listint start =intervals.get(0).start;int end =intervals.get(0).end;for (Interval i : intervals) {if (end <i.start) {res.add(newInterval(start, end)); start =i.start; end =i.end; } else { end =Math.max(end,i.end); } }// add final oneres.add(newInterval(start, end));return res; }}