LeetCode Merge Intervals

本文介绍了一种有效的合并区间算法,该算法首先对区间列表进行排序,优先考虑开始时间,并在开始时间相同时按结束时间排序。之后通过迭代过程合并所有重叠区间,最终返回简化后的区间列表。

Description:

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].


Solution:

Just sort the interval list, begin time has a higher priority, and if they are the same for two intervals, then sort this list with its end time, and later end time will have higher proirity. After sorting like this:

<1,9>, <1,4>, <1,3>, <2,9>, <2,2>, <10,11>

Then iterate from the first one, use an index 'startTime' and 'endTime' to keep the current new interval's start and end. And if current endTime is bigger than listnode's start, end this current new interval, and start a new one.


import java.io.*;
import java.util.*;

class Solution {
	public List<Interval> merge(List<Interval> intervals) {
		if (intervals == null)
			return intervals;

		intervals.add(new Interval(-1, -1));

		Comparator<Interval> comp = new Comparator<Interval>() {
			public int compare(Interval a, Interval b) {
				if (a.end == b.end) {
					return a.start - b.start;
				}
				return b.end - a.end;
			}
		};

		Collections.sort(intervals, comp);

		LinkedList<Interval> neoList = new LinkedList<Interval>();

		int startTime = intervals.get(0).start;
		int endTime = intervals.get(0).end;
		Interval interval;
		for (Iterator<Interval> ite = intervals.iterator(); ite.hasNext();) {
			interval = ite.next();
			if (interval.end < startTime) {
				neoList.add(new Interval(startTime, endTime));
				startTime = interval.start;
				endTime = interval.end;
			} else {
				startTime = Math.min(startTime, interval.start);
			}
		}

		return neoList;
	}
}

class Interval {
	int start, end;

	public Interval(int a, int b) {
		start = a;
		end = b;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值