题目来源:https://leetcode.com/problems/merge-intervals/
问题描述
56. Merge Intervals
Medium
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 considered overlapping.
------------------------------------------------------------
题意
给定一个由Interval(由start和end)组成的数列,合并可以合并的Intervals
------------------------------------------------------------
思路
首先将Interval按start从小到大排序,如果后一个Interval的start <= 前一个Interval的end,则merge这两个Interval. merge的时候注意要两个Interval的end不一定是后一个Interval的end,应该在前一个Interval和后一个Interval的end的较大者。
------------------------------------------------------------
代码
/**
* 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) {
intervals.sort(new Comparator<Interval>() {
@Override
public int compare(Interval intv1, Interval intv2)
{
return intv1.start - intv2.start;
}
});
Interval intv = null;
List<Interval> ret = new LinkedList<Interval>();
for (Interval item: intervals)
{
if (intv == null)
{
intv = new Interval(item.start, item.end);
}
else
{
if (item.start <= intv.end)
{
intv.end = Math.max(item.end, intv.end);
}
else
{
ret.add(intv);
intv = new Interval(item.start, item.end);
}
}
}
if (intv != null)
{
ret.add(intv);
}
return ret;
}
}