Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9]
, insert and merge [2,5]
in as [1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge [4,9]
in as [1,2],[3,10],[12,16]
.
This is because the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
上次做了Merge Interval的题目,这次的多了个插入,两题本质思路是一样的,无非在上次的代码基础上先将给的这个区间添加到到已有的intervals集合的最后面,再按照之前Merge的步骤(先排序,再将排完序的interval放入一个新的ArrayList中去)就实现了Insert和Merge的过程。比较器的写法是一个难点。
代码如下
/**
* 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; }
* }
*/
public class Solution {
public List insert(List intervals, Interval newInterval) {
intervals.add(newInterval);
// if(intervals==null |intervals.size()==0) return intervals;
ArrayList result = new ArrayList();
Collections.sort(intervals,new Comparator() {
// @Override
public int compare(Interval o1,Interval o2) {
if(o1.start == o2.start) {
return o1.end-o2.end;
} return o1.start-o2.start;
}
//比较器是一个接口,有2个方法,一个是equals,另一个是compare,所以实现这个接口要重写这2个方法,由于每个对象都是 //继承自Object对象,自身都有equals方法(相当于已重写),故只需重写compare方法即可
});
for(Interval interval :intervals) {
int last = result.size();
if(last==0||result.get(last-1).end=interval.start) {
result.get(last-1).end = Math.max(result.get(last-1).end,interval.end);
}
}
return result;
}
}
下面顺便附上Merge Interval的题目
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]
.