|
| 1 | +/** |
| 2 | + * 1272. Remove Interval |
| 3 | + * https://leetcode.com/problems/remove-interval/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A set of real numbers can be represented as the union of several disjoint intervals, |
| 7 | + * where each interval is in the form [a, b). A real number x is in the set if one of |
| 8 | + * its intervals [a, b) contains x (i.e. a <= x < b). |
| 9 | + * |
| 10 | + * You are given a sorted list of disjoint intervals intervals representing a set of |
| 11 | + * real numbers as described above, where intervals[i] = [ai, bi] represents the interval |
| 12 | + * [ai, bi). You are also given another interval toBeRemoved. |
| 13 | + * |
| 14 | + * Return the set of real numbers with the interval toBeRemoved removed from intervals. |
| 15 | + * In other words, return the set of real numbers such that every x in the set is in |
| 16 | + * intervals but not in toBeRemoved. Your answer should be a sorted list of disjoint |
| 17 | + * intervals as described above. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[][]} intervals |
| 22 | + * @param {number[]} toBeRemoved |
| 23 | + * @return {number[][]} |
| 24 | + */ |
| 25 | +var removeInterval = function(intervals, toBeRemoved) { |
| 26 | + const result = []; |
| 27 | + const [removeStart, removeEnd] = toBeRemoved; |
| 28 | + |
| 29 | + for (const [start, end] of intervals) { |
| 30 | + if (end <= removeStart || start >= removeEnd) { |
| 31 | + result.push([start, end]); |
| 32 | + } else { |
| 33 | + if (start < removeStart) { |
| 34 | + result.push([start, removeStart]); |
| 35 | + } |
| 36 | + if (end > removeEnd) { |
| 37 | + result.push([removeEnd, end]); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return result; |
| 43 | +}; |
0 commit comments