Пример 1: Ввод: интервалы = [[1,3], [2,6], [8,10], [15,18]] Вывод: [[1,6], [8,10], [15,18]] Объяснение: Поскольку интервалы [1,3] и [2,6] совпадают, объединяют их в [1,6]. Пример 2: Ввод: интервалы = [[1,4],[4,5]] Вывод: [[1,5]] Объяснение: Интервалы [1,4] и [4,5] считаются перекрывающимися. Примечание. Типы ввода были изменены 15 апреля 2019 года. Пожалуйста, сбросите в определение кода по умолчанию, чтобы получить новый метод подписи.
Ограничения: интервалы [i] [0] [i] [1]
var merge = function(intervals) {
if(intervals.length <= 1) return intervals;
// sort the array so earlier start times are at the beginning
intervals = intervals.sort((a,b) => a[0] - b[0])
let output = [intervals[0]];
let current = output[0];
// If the current interval's end time is greater than or equal
// to the next interval's start time, then we know there is an
// overlap and we merge them.
// If there is no overlap, then we add the next interval to the
// list of intervals in our output array and repeat the process
// until we go through the entire list of intervals.
for(let i = 1; i< intervals.length;i++) {
const next = intervals[i]
if(current[1] >= next[0]) {
current[1] = Math.max(current[1], next[1]);
} else {
current = next;
output.push(current);
}
}
return output;
};
Оригинал: “https://dev.to/cod3pineapple/56-merge-intervals-ko3”