Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 0580702

Browse files
committed
Add solution #57
1 parent e776ebe commit 0580702

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

0057-insert-interval.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 57. Insert Interval
3+
* https://leetcode.com/problems/insert-interval/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array of non-overlapping intervals intervals where
7+
* intervals[i] = [starti, endi] represent the start and the end of the
8+
* ith interval and intervals is sorted in ascending order by starti.
9+
* You are also given an interval newInterval = [start, end] that
10+
* represents the start and end of another interval.
11+
*
12+
* Insert newInterval into intervals such that intervals is still sorted
13+
* in ascending order by starti and intervals still does not have any
14+
* overlapping intervals (merge overlapping intervals if necessary).
15+
*
16+
* Return intervals after the insertion.
17+
*/
18+
19+
/**
20+
* @param {number[][]} intervals
21+
* @param {number[]} newInterval
22+
* @return {number[][]}
23+
*/
24+
var insert = function(intervals, newInterval) {
25+
const result = [];
26+
27+
for (let i = 0; i < intervals.length; i++) {
28+
if (newInterval[1] < intervals[i][0]) {
29+
result.push(newInterval);
30+
return [...result, ...intervals.slice(i)];
31+
} else if (newInterval[0] > intervals[i][1]) {
32+
result.push(intervals[i]);
33+
} else {
34+
newInterval = [
35+
Math.min(newInterval[0], intervals[i][0]),
36+
Math.max(newInterval[1], intervals[i][1]),
37+
];
38+
}
39+
}
40+
41+
result.push(newInterval);
42+
return result;
43+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
50|[Pow(x, n)](./0050-powx-n.js)|Medium|
5656
53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy|
5757
54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium|
58+
57|[Insert Interval](./0057-insert-interval.js)|Medium|
5859
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
5960
62|[Unique Paths](./0062-unique-paths.js)|Medium|
6061
66|[Plus One](./0066-plus-one.js)|Easy|

0 commit comments

Comments
 (0)