Skip to content

Commit 41061a3

Browse files
committed
finish 57
1 parent 0313d60 commit 41061a3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

57. Insert Interval.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 57. Insert Interval
3+
*
4+
* Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
5+
*
6+
* You may assume that the intervals were initially sorted according to their start times.
7+
*
8+
* Example 1:
9+
*
10+
* Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
11+
* Output: [[1,5],[6,9]]
12+
*
13+
* Example 2:
14+
*
15+
* Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
16+
* Output: [[1,2],[3,10],[12,16]]
17+
* Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
18+
*/
19+
20+
/**
21+
* Definition for an interval.
22+
* function Interval(start, end) {
23+
* this.start = start;
24+
* this.end = end;
25+
* }
26+
*/
27+
/**
28+
* @param {Interval[]} intervals
29+
* @param {Interval} newInterval
30+
* @return {Interval[]}
31+
*/
32+
var insert = function(intervals, newInterval) {
33+
var len = intervals.length;
34+
var i = 0;
35+
var res = [];
36+
while (i < len && intervals[i].end < newInterval.start) {
37+
res.push(intervals[i]);
38+
i++;
39+
}
40+
while (i < len && intervals[i].start <= newInterval.end) {
41+
newInterval.start = Math.min(newInterval.start, intervals[i].start);
42+
newInterval.end = Math.max(newInterval.end, intervals[i].end);
43+
i++;
44+
}
45+
res.push(newInterval);
46+
while (i < len) {
47+
res.push(intervals[i]);
48+
i++;
49+
}
50+
return res;
51+
};

0 commit comments

Comments
 (0)