Skip to content

Commit a204081

Browse files
committed
🔥 Insert Interval
1 parent 46579c2 commit a204081

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,4 @@ Solutions of LeetCode Blind 75 Problems in JavaScript
2828
| [Pacific Atlantic Water Flow]() | | | [:link:](https://leetcode.com/problems/pacific-atlantic-water-flow/) |
2929
| [Number of Islands](./number-of-islands.js) | <img src="https://img.shields.io/badge/-Medium-orange" /> | `Array`, `Matrix`, `DFS`, `BFS` | [:link:](https://leetcode.com/problems/number-of-islands/) |
3030
| [Longest Consecutive Sequence](./longest-consecutive-sequence.js) | <img src="https://img.shields.io/badge/-Medium-orange" /> | `Array`, `HashTable` | [:link:](https://leetcode.com/problems/longest-consecutive-sequence/) |
31+
| [Insert Interval](./insert-interval.js) | <img src="https://img.shields.io/badge/-Medium-orange" /> | `Array` | [:link:](https://leetcode.com/problems/insert-interval/) |

insert-interval.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const insert = (intervals, newInterval) => {
2+
const result = [];
3+
4+
for (let i = 0; i < intervals.length; i++) {
5+
const interval = intervals[i];
6+
7+
if (newInterval[0] > interval[1]) {
8+
result.push(interval);
9+
} else if (newInterval[1] < interval[0]) {
10+
result.push(newInterval);
11+
return result.concat(intervals.splice(i));
12+
} else {
13+
newInterval = [
14+
Math.min(newInterval[0], interval[0]),
15+
Math.max(newInterval[1], interval[1]),
16+
];
17+
}
18+
}
19+
20+
result.push(newInterval);
21+
return result;
22+
};

0 commit comments

Comments
 (0)