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]
.
思路:先将 newInterval插入链表中,转化成LeetCode 55题 Merge Intervals
import java.util.*;
/**
* 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; }
* }
*/
@SuppressWarnings("rawtypes")
class MyComprator implements Comparator {
public int compare(Object arg0, Object arg1) {
Interval t1 = (Interval) arg0;
Interval t2 = (Interval) arg1;
if (t1.start == t2.start && t1.end == t2.end) return 0;
if (t1.start != t2.start)
return t1.start > t2.start ? 1 : -1;
else
return t1.end > t2.end ? 1 : -1;
}
}
public class Solution {
@SuppressWarnings("unchecked")
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
intervals.add(newInterval);
Interval[] arr = intervals.toArray(new Interval[intervals.size()]);
List<Interval> result=new ArrayList<Interval>();
Arrays.sort(arr, new MyComprator());
Interval mover = arr[0];
for(int i=1;i<arr.length;i++){
if(mover.end<arr[i].start) {
result.add(mover);
mover = arr[i];
}else{
mover.end = Math.max(mover.end,arr[i].end);
}
}
result.add(mover);
return result;
}
}