在 JavaScript 中将新区间插入已排序的区间数组
在本题中,我们将区间定义为由两个数字组成的数组,其中第一个数字始终小于第二个数字。
例如:
[4, 6], [2, 3], [6, 8], [2, 7], [1, 8] are all examples of valid intervals.
假设我们有一个区间数组,它根据其起始时间(每个区间的第一个元素)排序。
数组中的区间是不重叠的,这意味着对于任意两个相邻区间:
[m, n], [x, y] m < n < x < y
因此,这个区间数组的一个例子可以是:
const arr = [[ 2, 4], [5, 7], [9, 10], [13, 17]];
我们需要编写一个 JavaScript 函数,该函数将这样一个区间数组作为第一个参数,并将单个区间作为第二个参数。
然后,该函数应将区间插入到数组中的正确位置,并保持数组的不重叠属性。
如果需要,我们可以合并数组中的两个或多个区间,以保持数组区间不重叠。
例如,如果对于上述区间数组,我们需要插入的区间是 [6, 13],则输出应如下所示:
const output = [[2, 4], [5, 17]];
示例
以下是代码:
const arr = [[2, 4], [5, 7], [9, 10], [13, 17]];
const interval = [6, 13];
const insertWithin = (arr = [], interval = []) => {
const res = [];
let ind = 0;
while (arr[ind] && arr[ind][1] < interval[0]) {
res.push(arr[ind]);
++ind;
};
let start = interval[0];
let end = interval[1];
while (arr[ind] && arr[ind][0] <= interval[1]) {
start = Math.min(start, arr[ind][0]);
end = Math.max(end, arr[ind][1]);
++ind;
}
res.push([start, end]);
while (arr[ind]) {
res.push(arr[ind]);
++ind;
}
return res;
};
console.log(insertWithin(arr, interval));输出
以下是控制台输出:
[[2, 4], [5, 17]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP