ying-study
ying-study copied to clipboard
12. 求数组上的交集
例:
[2, 6]、[1, 4]、[5, 8]
交集为:
[2, 4]、[5, 6]
注:
第一个解的意思是 [2, 6]、[1, 4]
的区间为[2, 4]
第二个解的意思是 [2, 6]、[5, 8]
的区间为[5, 6]
没看懂题目呀,4,5怎么出来的呀
没看懂题目呀,4,5怎么出来的呀
第一个解的意思是 [2, 6]、[1, 4]
的区间为[2, 4]
第二个解的意思是 [2, 6]、[5, 8]
的区间为[5, 6]
/**
* 求范围交集
* 给定 [2, 6]、 [1, 4]、[5, 8]
* 输出 [2, 4]、[5, 6]
*/
/**
思路:
1.算出组合数 C(m, n) = m! / n!(m - n)!
2.取组合数比较算范围交集
3.返回结果
*/
const a = [2, 6];
const b = [1, 4];
const c = [5, 8];
// 题意 C(m, n) 从3个数组中取2个数组比较交集,得出 n = 2
const arr = [a, b, c];
const m = arr.length;
const n = 2;
// 阶乘递归
function factor(Number) {
let res = "";
const fn = (Number, total = 1) => {
if (Number === 1) return (res = total);
total = Number * total;
fn(Number - 1, total);
};
fn(Number);
return res;
}
// 组合数
const factorNum = factor(m) / (factor(n) * factor(m - n));
// 算交集范围
function deal(arr, n, factorNum) {
const res = [];
for (let i = 0; i < factorNum; i++) {
const current = arr[i];
const nextIndex = i + n - 1;
const next = arr[arr.hasOwnProperty(nextIndex) ? nextIndex : nextIndex - arr.length];
const [min1, max1] = current.sort((a, b) => a - b);
const [min2, max2] = next.sort((a, b) => a - b);
if (max1 >= min2 && min1 <= min2) res.push([min2, max1]);
else if (max2 >= min1 && min2 <= min1) res.push([min1, max2]);
else if (max2 >= max1 && min2 <= min1) res.push([min2, max2]);
else if (max1 >= max2 && min1 <= min2) res.push([min1, max1]);
else res.push("");
}
const filterRes = res.filter((item) => item !== "");
return filterRes;
}
// 调用
const res = deal(arr, n, factorNum);
console.log(...res);