微不足道的算法是:
-
从集合中创建3(或x)个不同范围的所有组合。
-
对于每个组合,计算三者的交集。
-
返回交叉点的并集。
// ranges: Array<{ from: number, to: number }>, x: number
const combinations = _.combinations(ranges, x) // lodash.combinations
const intersections = combinations.map(combination => combination.reduce(
(intersection, range) => ({
from: Math.max(intersection.from, range.from),
to: Math.min(intersection.to, range.to)
})
{ from: Number.MIN_SAFE_INTEGER, to: Number.MAX_SAFE_INTEGER }
)).filter(({ from, to }) => from < to)
// ... (union is trivial too)
我不知道它是否能以较低的时间复杂度完成,但由于你没有分享任何你实际尝试过的信息,我想我应该投票结束而不是回答。