我发现了类似的问题,但批准的答案对我的问题不起作用。
我有一个输入:范围对象数组,每个对象包含:
start
:整数,范围的开始,end
:整数,范围的结尾。输出应为:
一系列非重叠范围对象,覆盖与从最小起点到最大起点排序的输入相同的范围。如果出现以下情况,则两个范围不重叠:
range1.start <= range2.start
和range1.end >= range2.start
输入:
[
{ start: 8, end: 10 },
{ start: 5, end: 7 },
{ start: 9, end: 12 },
{ start: 2, end: 6 },
]
输出:
[
{ start: 2, end: 7 },
{ start: 8, end: 12 }
]
正如我所提到的,我尝试在网上应用解决方案来合并重叠间隔,但他们没有完成这项工作。
谢谢。
答案 0 :(得分:2)
您可以按start
和end
对数组进行排序,并对已排序的数组进行迭代,并检查范围是否重叠。
var data = [{ start: 8, end: 10 }, { start: 5, end: 7 }, { start: 9, end: 12 }, { start: 2, end: 6 }],
result = data
.sort(function (a, b) { return a.start - b.start || a.end - b.end; })
.reduce(function (r, a) {
var last = r[r.length - 1] || [];
if (last.start <= a.start && a.start <= last.end) {
if (last.end < a.end) {
last.end = a.end;
}
return r;
}
return r.concat(a);
}, []);
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 1 :(得分:0)
var ranges = [
{ start: 8, end: 10 },
{ start: 5, end: 7 },
{ start: 9, end: 12 },
{ start: 2, end: 6 }
];
function merge(ranges) {
// first, sort the ranges
ranges.sort((a, b) => a.start - b.start);
// take two ranges, and merges them together
var mergeFn = (a, b) => ({start: Math.min(a.start, b.start), end: Math.max(a.end, b.end)});
// check if two ranges overlap
var overlapFn = (a, b) => (b.start <= a.end);
// make current the first item of the array (start the array from 1 to not check the first item against itself)
var current = ranges[0];
var result = [];
for(var i = 1; i < ranges.length; i++) {
if(overlapFn(current, ranges[i])) // if the current range overlapping with this range
current = mergeFn(current, ranges[i]); // merge them into the current range
else { // if not
result.push(current); // add the current accumulated range as result
current = ranges[i]; // start accumulating another one from this range
}
}
result.push(current); // add the last result
return result;
}
console.log(merge(ranges));
&#13;