首先要考虑区间的顺序,给到你的区间是乱序的,所以说首先要排序。排序的逻辑也很简单,只要按照起始位置排序就可以了。比如本来区间的顺序是这样的:
[0] [1] [2] [3] [4] [5]
0 [0 1]
1 [3 4]
2 [0 2]
3 [1 2]
4 [3 5]
如果这样就按照从上到下的索引顺序开始合并,是无法兼顾所有情况的。因为有的区间由于所在的数组索引不相邻,无法合并,这样就没有办法有规律的操作。而按照每个区间的左端点升序排序过后:
[0] [1] [2] [3] [4] [5]
0 [0 1]
2 [0 2]
3 [1 2]
1 [3 4]
4 [3 5]
这样就可以按照从前到后的顺序进行合并而不用考虑跳过不跳过的问题。
合并的话就相对直接一点,对于某两个区间,如果后者的左端点小于等于前者的右端点,那么它们就可以合并。但这时候有两种情况:
Scenario 1
Interval A [10, 11, 12, 13]
Interval B [11, 12, 13, 14, 15]
Scenario 2
Interval A [10, 11, 12, 13]
Interval B [11, 12]
所以这时候就要判断一下二者之间谁的右端点大才行。
代码如下:
const merge = (intervals) => {
intervals.sort((a, b) => a[0] - b[0]);
const res = [];
// begin with first one
let temp = intervals[0];
for (const interval of intervals) {
// can merge
if (interval[0] <= temp[1]) {
// determin which point to use
temp[1] = Math.max(temp[1], interval[1]);
} else {
// push what we have right now
res.push(temp);
// update temp with current one
temp = interval;
}
}
// always push in the temp because we did not push in the loop
// during the final iteration
res.push(temp);
return res;
};