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].
遍历已有vector,如果当前interval小于newinterval,插入当前;如果当前interval大于newInterval,则插入newInterval及当前;如果两者重叠,merge以后插入新的interval。
实现中之所以重新new了一个vector来存放结果的原因,是不愿意破坏传入参数。
在原有的vector上面直接修改的话,唯一的区别就是,一旦发现当前interval大于newInterval,就应该return了。
https://leetcode.com/problems/insert-interval/discuss/21602/Short-and-straight-forward-Java-solution
Extended: In case we want to add the interval in place:
出题的人,添加了一个附属条件,这些interval是在一个圆环上。比如当环是[1, 255]时,如果两个Interval分别是[1,234], [222, 4], Merge最后的结果是[1,4]。这个条件完全是个干扰,因为如果真的在逻辑中考虑环的话,非常麻烦,而且在环上做循环合并的话,无法判断何时该终止循环。当时我的解法就是,如果第一个是跨越0点的话(比如[234,7]),把它拆分成两个interval([234, 255],[1,7]), 然后把[1,7]插到队头,[234,255]插到队尾。 从[1,7]开始往后合并,合并完成后,再检查对头及队尾,需要的话,再合并一次即可。
X.
https://leetcode.com/discuss/93980/java-binary-search-solution-beats-with-clear-explaination
https://leetcode.com/discuss/42018/7-lines-3-easy-solutions
X. Not Good
https://leetcode.com/discuss/33249/short-java-code
Set newInterval to null
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> result = new ArrayList<Interval>(); for (Interval i : intervals) { if (newInterval == null || i.end < newInterval.start) result.add(i); else if (i.start > newInterval.end) { result.add(newInterval); result.add(i); newInterval = null; } else { newInterval.start = Math.min(newInterval.start, i.start); newInterval.end = Math.max(newInterval.end, i.end); } } if (newInterval != null) result.add(newInterval); return result; }
Read full article from LeetCode - Insert Interval | Darren's Blog
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].
遍历已有vector,如果当前interval小于newinterval,插入当前;如果当前interval大于newInterval,则插入newInterval及当前;如果两者重叠,merge以后插入新的interval。
实现中之所以重新new了一个vector来存放结果的原因,是不愿意破坏传入参数。
在原有的vector上面直接修改的话,唯一的区别就是,一旦发现当前interval大于newInterval,就应该return了。
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
ArrayList<Interval> result = new ArrayList<Interval>();
// No interval in the list
if (intervals == null || intervals.size() == 0) {
result.add(newInterval);
return result;
}
boolean added = false; // Indicate whether "newInterval" has been added
// Traverse the (sorted) intervals and merge intervals
// overlapping with "newInterval" if needed
for (Interval interval : intervals) {
if (interval.end < newInterval.start) // Non-overlapping intervals ahead "newInterval"
result.add(interval);
else if (interval.start > newInterval.end) { // Non-overlapping intervals behind "newInterval"
// If "newInterval" has not been added, add it before the current interval
if (!added) {
result.add(newInterval);
added = true;
}
result.add(interval);
} else { // Overlapping intervals
// Merge the current interval with "newInterval", and reflect it in "newInterval"
newInterval.start = Math.min(newInterval.start, interval.start);
newInterval.end = Math.max(newInterval.end, interval.end);
}
}
// In case "newInterval" has not been added in the loop
if (!added)
result.add(newInterval);
return result;
}
Code from http://www.programcreek.com/2012/12/leetcode-insert-interval/public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { ArrayList<Interval> result = new ArrayList<Interval>(); for(Interval interval: intervals){ if(interval.end < newInterval.start){ result.add(interval); }else if(interval.start > newInterval.end){ result.add(newInterval); newInterval = interval; }else if(interval.end >= newInterval.start || interval.start <= newInterval.end){ newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(newInterval.end, interval.end)); } } result.add(newInterval); return result; }
https://leetcode.com/problems/insert-interval/discuss/21602/Short-and-straight-forward-Java-solution
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> result = new LinkedList<>();
int i = 0;
// add all the intervals ending before newInterval starts
while (i < intervals.size() && intervals.get(i).end < newInterval.start)
result.add(intervals.get(i++));
// merge all overlapping intervals to one considering newInterval
while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
newInterval = new Interval( // we could mutate newInterval here also
Math.min(newInterval.start, intervals.get(i).start),
Math.max(newInterval.end, intervals.get(i).end));
i++;
}
result.add(newInterval); // add the union of intervals we got
// add all the rest
while (i < intervals.size()) result.add(intervals.get(i++));
return result;
}
Instead of using
new
operator, why not just do newInterval.start =
. This will make sure you're not creating new objects in a while loop. Great solution though! :)
No need to use additional memory. In place solution with little bit change.
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {``
int i=0;
while(i<intervals.size() && intervals.get(i).end<newInterval.start) i++;
while(i<intervals.size() && intervals.get(i).start<=newInterval.end){
newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end));
intervals.remove(i);
}
intervals.add(i,newInterval);
return intervals;
}
Extended: In case we want to add the interval in place:
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; }
出题的人,添加了一个附属条件,这些interval是在一个圆环上。比如当环是[1, 255]时,如果两个Interval分别是[1,234], [222, 4], Merge最后的结果是[1,4]。这个条件完全是个干扰,因为如果真的在逻辑中考虑环的话,非常麻烦,而且在环上做循环合并的话,无法判断何时该终止循环。当时我的解法就是,如果第一个是跨越0点的话(比如[234,7]),把它拆分成两个interval([234, 255],[1,7]), 然后把[1,7]插到队头,[234,255]插到队尾。 从[1,7]开始往后合并,合并完成后,再检查对头及队尾,需要的话,再合并一次即可。
X.
https://leetcode.com/discuss/93980/java-binary-search-solution-beats-with-clear-explaination
The idea is using binary search to find the position that the newInterval to be inserted.
Since the original intervals are sorted and disjoint, we can apply binary search to find the insertion index of newInterval.start (by interval.start), and to find the insertion index of newInterval.end(by interval.end), 【see LeeCode problem #35】. Then remove the overlapped elements of the list and merge the newInterval with boundary elements on two sides.
Complexity: O(log n) in time (in fact, depending on the implement of the access method list.get(i) and of list.subList(int, int).clear()); O(1) in space.
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
/**
* Since the original list is sorted and all intervals are disjoint,
* apply binary search to find the insertion index for the new
* interval. [LC35]
*
* 1. Find insIdx=the insertion index of new.start, i.e., the first
* index i such that list.get(i).start>=new.start.
*
* 2. Find nxtIdx=the insertion index of new.end, i.e., the first
* index i such that list.get(i).end>=new.end.
*
* 3. Remove all elements of the list with indices insIdx<=i<nxtIdx.
*
* 4. Merge new with list.get(insIdx-1) or list.get(nxtIdx) or both.
*/
int n = intervals.size();
if (n == 0) {
intervals.add(newInterval);
return intervals;
}
int low = 0, high = n - 1, mid = 0;
int temp, target = newInterval.start;
while (low <= high) {
mid = (low + high) / 2;
temp = intervals.get(mid).start;
if (temp == target)
break;
if (temp < target)
low = mid + 1;
else
high = mid - 1;
}
// insIdx = the index where new interval to be inserted
int insIdx = (low <= high) ? mid : low;
Interval pre = (insIdx == 0) ? null : intervals.get(insIdx - 1);
// 0<=insIdx<=n, pre=[insIdx-1], pre.start<new.start
low = insIdx;
high = n - 1;
target = newInterval.end;
while (low <= high) {
mid = (low + high) / 2;
temp = intervals.get(mid).end;
if (temp == target)
break;
if (temp < target)
low = mid + 1;
else
high = mid - 1;
}
// nxtIdx= the next index after the inserted new interval
int nxtIdx = (low <= high) ? mid : low;
Interval nxt = (nxtIdx == n) ? null : intervals.get(nxtIdx);
// insIdx<=nxtIdx<=n, nxt=[nxtIdx], nxt.end>=new.end
// [0]...[insIdx-1] <--> [insIdx]...[nxtIdx-1][nxtIdx]...[n]
intervals.subList(insIdx, nxtIdx).clear();
// check whether newInterval can be merged with pre or nxt
boolean isMerged = false, isMerged2 = false;
if (insIdx > 0 && pre.end >= newInterval.start) {
pre.end = Math.max(pre.end, newInterval.end);
isMerged = true;
}
if (nxtIdx < n && newInterval.end >= nxt.start) {
nxt.start = Math.min(nxt.start, newInterval.start);
isMerged2 = isMerged;
isMerged = true;
}
if (!isMerged) {
intervals.add(insIdx, newInterval);
return intervals;
}
// merged with pre or nxt or both, deal with the both case
if (isMerged2 && pre.end >= nxt.start) {
nxt.start = pre.start; // pre.start < new.start, nxt.start;
intervals.remove(insIdx - 1); // remove pre
}
return intervals;
}https://leetcode.com/discuss/42018/7-lines-3-easy-solutions
def insert(self, intervals, newInterval):
s, e = newInterval.start, newInterval.end
left, right = [], []
for i in intervals:
if i.end < s:
left += i,
elif i.start > e:
right += i,
else:
s = min(s, i.start)
e = max(e, i.end)
return left + [Interval(s, e)] + right
https://leetcode.com/discuss/33249/short-java-code
Set newInterval to null
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> result = new ArrayList<Interval>(); for (Interval i : intervals) { if (newInterval == null || i.end < newInterval.start) result.add(i); else if (i.start > newInterval.end) { result.add(newInterval); result.add(i); newInterval = null; } else { newInterval.start = Math.min(newInterval.start, i.start); newInterval.end = Math.max(newInterval.end, i.end); } } if (newInterval != null) result.add(newInterval); return result; }
Read full article from LeetCode - Insert Interval | Darren's Blog