Created
April 19, 2021 20:50
-
-
Save MohammedALREAI/2cceeaba7da631a60815196793790592 to your computer and use it in GitHub Desktop.
57. Insert Interval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function insert(intervals: number[][], newInterval: number[]): number[][] { | |
| let i = 0; | |
| while (i < intervals.length) { | |
| const [a, b] = intervals[i]; | |
| const [c, d] = newInterval; | |
| if ( | |
| (a >= c && a <= d) || | |
| (b >= c && b <= d) || | |
| (c >= a && c <= b) || | |
| (d >= a && d <= b) | |
| ) { | |
| newInterval = mergeIntervals(intervals[i], newInterval); | |
| intervals.splice(i, 1); | |
| } else { | |
| i++; | |
| } | |
| } | |
| intervals.push(newInterval); | |
| intervals.sort((a, b) => a[0] - b[0]); | |
| return intervals; | |
| } | |
| const mergeIntervals = (int1: number[], int2: number[]) => [ | |
| Math.min(int1[0], int2[0]), | |
| Math.max(int1[1], int2[1]), | |
| ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment