Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[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: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
这道题看例子就观察到如果是按照区间最小值排过序的话会比较好做,不然的话找来找去复杂度应该会很高吧,排过序最多也就是O(nlogn)。排序之后就比较好想了,如果后一个区间的起始比前一个区间的最后要小,那证明有覆盖,这时需要合并区间。合并还要看一下前后区间的末尾的情况,要取更大的那个作为合并后的末尾。如果后一个区间的起始没有覆盖前一个区间的末尾,那么就是一个新的区间。把之前的区间存到结果里面,并继续寻找新区间就好。
Java
/** * 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; } * } */ class Solution { public List<Interval> merge(List<Interval> intervals) { int len = intervals.size(); if (len <= 1) return intervals; Collections.sort(intervals, new cmp()); List<Interval> res = new ArrayList<Interval>(); int start = intervals.get(0).start, end = intervals.get(0).end; for (int i = 1; i < len; i++) { if (intervals.get(i).start <= end) { end = end > intervals.get(i).end ? end : intervals.get(i).end; } else { res.add(new Interval(start, end)); start = intervals.get(i).start; end = intervals.get(i).end; } } res.add(new Interval(start, end)); return res; } class cmp implements Comparator<Interval> { public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } } }
原文地址:https://www.cnblogs.com/tengdai/p/9249079.html
时间: 2024-10-12 18:38:51