这是一张说明我的意思的图片:
基本上我想将set1合并到set2中,但是不允许存在set1的每个间隔,除非它包含在set2的间隔范围内。
非常感谢任何建议!
PS:我的下一个任务是弄清楚如何将 n 数量的* set1 * s(即可能相互重叠的绿色层)合并到一个具有相同规则的set2中。 ..但我先从这开始!
答案 0 :(得分:0)
为了有效地实现第二步,您可以使用第一个坐标对set2中的间隔进行排序,并使用二进制搜索。第3步https://www.geeksforgeeks.org/merging-intervals/
答案 1 :(得分:0)
以下是JavaScript中这种合并的算法 - 它应该很容易在其他编程语言中重现:
function merge(segments1, segments2) {
const result = [];
let i = -1, start1 = -Infinity, end1 = -Infinity,
j = -1, start2 = -Infinity; end2 = -Infinity;
while (i < segments1.length || j < segments2.length) {
if (end1 <= start2) { // get next from segments1
i++;
start1 = i < segments1.length ? segments1[i][0] : Infinity;
end1 = i < segments1.length ? segments1[i][1] : Infinity;
} else if (end2 <= start1) { // flush and get next from segments2
if (start2 < end2) result.push([start2, end2]);
j++;
start2 = j < segments2.length ? segments2[j][0] : Infinity;
end2 = j < segments2.length ? segments2[j][1] : Infinity;
} else { // overlap
if (start2 < start1) {
result.push([start2, start1]);
start2 = start1;
}
start1 = Math.min(end2, end1);
result.push([start2, start1]);
start2 = start1;
}
}
return result;
}
// Sample input
const segments1 = [[6, 7], [8, 11], [12, 14], [15, 18], [19, 20], [22, 23],
[25, 26], [27, 28], [30, 31], [33, 35]],
segments2 = [[6, 10], [11, 14], [16, 17], [18, 21], [22, 24], [24, 26],
[27, 28], [29, 31], [33, 34], [35, 36]];
// Merge and output
const result = merge(segments1, segments2);
console.log(JSON.stringify(result));
要合并多组线段,您只需调用上述函数:
merged = merge(green1, grey)
merged = merge(green2, merged)
merged = merge(green3, merged)
// ... etc