合并所有覆盖的区间,一道对逻辑思维要求比较高的题。
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].
http://oj.leetcode.com/problems/insert-interval/
解题报告:
新区间是新输入的线段,对原有的线段ArrayList进行遍历。
考虑以下情况:
如果新区间的end < 当前区间的start,不用找下去了,把新区间插入到当前区间的前面,然后返回。
如果当前区间的end小于新区间的start,继续遍历找下一个区间。
如果当前区间和新区间发生重合,则start取两者最小的start,end取两者最大的end,生成一个新的区间。
继续遍历。
如果遍历一直到末尾也没发生区间重合,就把新区间插入到原来ArrayList的末尾。
里面用到了几个通过iterator操作ArrayList的函数:在遍历ArrayList的过程中想删除其中某个element、遍历的过程中插入某个element,有空慢慢总结一下。
AC代码:
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].
http://oj.leetcode.com/problems/insert-interval/
解题报告:
新区间是新输入的线段,对原有的线段ArrayList进行遍历。
考虑以下情况:
如果新区间的end < 当前区间的start,不用找下去了,把新区间插入到当前区间的前面,然后返回。
如果当前区间的end小于新区间的start,继续遍历找下一个区间。
如果当前区间和新区间发生重合,则start取两者最小的start,end取两者最大的end,生成一个新的区间。
继续遍历。
如果遍历一直到末尾也没发生区间重合,就把新区间插入到原来ArrayList的末尾。
里面用到了几个通过iterator操作ArrayList的函数:在遍历ArrayList的过程中想删除其中某个element、遍历的过程中插入某个element,有空慢慢总结一下。
AC代码:
public class Solution {
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
if(intervals==null||newInterval==null) {
return intervals;
}
if(intervals.size()==0) {
intervals.add(newInterval);
return intervals;
}
ListIterator<Interval> it = intervals.listIterator();
while(it.hasNext()) {
Interval tmpInterval = it.next();
if(newInterval.end<tmpInterval.start) {
it.previous();
it.add(newInterval);
return intervals;
} else {
if(tmpInterval.end<newInterval.start) {
continue;
} else {
newInterval.start = Math.min(tmpInterval.start, newInterval.start);
newInterval.end = Math.max(tmpInterval.end, newInterval.end);
it.remove();
}
}
}
intervals.add(newInterval);
return intervals;
}
}

本文介绍了一种区间合并算法,该算法能够将一个新区间插入到已排序的非重叠区间集合中,并在必要时进行合并。通过具体示例展示了如何处理新区间与已有区间之间的各种重合情况。
263

被折叠的 条评论
为什么被折叠?



