这个函数的运行时复杂度是多少?
Which is the runtime complexity of this function?
第一次听说big O,所以不是很清楚,我个人认为这是一个O(n^2),因为它对每个对象的using filter然后包括另一个数组的每个对象..
function subset(a, b) {
const result = a.filter(a => b.includes(a));
return (result.length == b.length) ? true : false;
}
const array1 = ["a", "b", "c", "d", "e", "f", "g"];
const array2 = ["a", "b", "e", "g", "e"];
const isSubset = subset(array1, array2);
console.log(isSubset);
array1.size = n
array2.size = m
如果我们把它翻译成伪代码:
for each object1 in array1.size:
for each object2 in array2.size:
object2.includes(object1)
所以复杂度为 O(n*m)。
第一次听说big O,所以不是很清楚,我个人认为这是一个O(n^2),因为它对每个对象的using filter然后包括另一个数组的每个对象..
function subset(a, b) {
const result = a.filter(a => b.includes(a));
return (result.length == b.length) ? true : false;
}
const array1 = ["a", "b", "c", "d", "e", "f", "g"];
const array2 = ["a", "b", "e", "g", "e"];
const isSubset = subset(array1, array2);
console.log(isSubset);
array1.size = n
array2.size = m
如果我们把它翻译成伪代码:
for each object1 in array1.size:
for each object2 in array2.size:
object2.includes(object1)
所以复杂度为 O(n*m)。