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]
.
Code:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* @author MohnSnow
* @time 2015年6月26日 下午4:10:08
*
*/
public class LeetCode57 {
/**
* @param argsmengdx
* -fnst
*/
public static class Interval {
int start;
int end;
Interval() {
start = 0;
end = 0;
}
Interval(int s, int e) {
start = s;
end = e;
}
public String toString() {
String result = "start:" + start + " end: " + end;
return result;
}
}
//616msAC---一次性优化通过
public static List<Interval> insert(List<Interval> intervals,
Interval newInterval) {
System.out.println("intervals: " + intervals);
System.out.println("newInterval: " + newInterval);
List<Interval> result = new ArrayList<Interval>();
result.add(newInterval);
for (Interval inter : intervals) {
if (newInterval.end < inter.start) {
newInterval = inter;
result.add(newInterval);
System.out.println("result1111: " + result);
} else if (newInterval.start > inter.end) {
int temp = newInterval.start;
newInterval.start = inter.start;
inter.start = temp;
temp = newInterval.end;
newInterval.end = inter.end;
inter.end = temp;
newInterval = inter;
result.add(newInterval);
System.out.println("result2222: " + result);
} else {
newInterval.end = Math.max(newInterval.end, inter.end);
newInterval.start = Math.min(newInterval.start, inter.start);
System.out.println("result3333: " + result);
}
}
return result;
}
public static void main(String[] args) {
Interval a = new Interval(2, 3);
Interval b = new Interval(6, 9);
Interval c = new Interval(9, 19);
Interval d = new Interval(15, 18);
List<Interval> intervals = new LinkedList<Interval>();
intervals.add(a);
intervals.add(b);
intervals.add(c);
intervals.add(d);
Interval newInterval = new Interval(10, 11);
System.out.println("merge: " + insert(intervals, newInterval));
}
}