|
| 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 | +}; |
0 commit comments