每天一道leetcode56-合并区间 分类:数组 中文链接: https://leetcode-cn.com/problems/merge-intervals/description/ 英文链接 https://leetcode.com/problems/merge-intervals/description/
给出一个区间的集合,请合并所有重叠的区间。 示例 1: 输入: [[1,3],[2,6],[8,10],[15,18]] 输出: [[1,6],[8,10],[15,18]] 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. 示例 2: 输入: [[1,4],[4,5]] 输出: [[1,5]] 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
思路
代码
class Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
}
public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if(o1.start > o2.start)
return 1;
else if(o1.start < o2.start)
return -1;
else
return 0;
}
});
int i = 0;
while(i < intervals.size())
{
if(i != intervals.size() - 1)
{
if(intervals.get(i).end >= intervals.get(i+1).start && intervals.get(i).end <= intervals.get(i+1).end)
{
int tempStart = intervals.get(i).start;
int tempEnd = intervals.get(i+1).end;
intervals.remove(i);
intervals.get(i).start = tempStart;
intervals.get(i).end = tempEnd;
}else if(intervals.get(i).end < intervals.get(i+1).start){
i++;
}else if(intervals.get(i).end > intervals.get(i+1).end){
intervals.remove(i+1);
i=i;
}
}else {
i++;
}
}
return intervals;
}
代码讲解