# Hard-题目28：57. Insert Interval

61人阅读 评论(0)

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].

/**
* 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 {
private class IntervalComparator implements Comparator<Interval> {
@Override
public int compare(Interval o1, Interval o2) {
// TODO Auto-generated method stub
if(o1.start<o2.start)
return -1;
else if(o1.start>o2.start)
return 1;
else {
if(o1.end<o2.end)
return -1;
else if(o1.end>o2.end)
return 1;
else {
return 0;
}
}
}

}
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> temp = merge(intervals);
Collections.sort(temp, new IntervalComparator());
return temp;
}
public List<Interval> merge(List<Interval> intervals) {
boolean[] x = new boolean[40000];
boolean[] dots = new boolean[40000];
int max = Integer.MIN_VALUE,min = Integer.MAX_VALUE;
List<Interval> list = new ArrayList<Interval>();
for(Interval interval : intervals) {
for(int i=interval.start;i<interval.end;i++) {
x[i]=true;
if(i<min)
min=i;
if(i>max)
max=i;
}
}

int i = min;
while(i<=max) {
if(!x[i]) {
i++;
continue;
}
int start=i,end=start;
while(x[end])
end++;
i=end;

}
for(Interval interval : intervals) {
int start = interval.start,end = interval.end;
if(start==end && !dots[interval.start]) {
dots[start] = true;
if(start==0 && !x[0])
else if(!x[start] && !x[start-1])
}

}
return list;
}
}

9ms,24.58%,5ms,26.17%

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：55804次
• 积分：3197
• 等级：
• 排名：第10667名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论