forEach函数的时间复杂度是多少? O(n + n m)或O(n + n n)?有一个循环,然后是嵌套循环。如果您能解释我将不胜感激
function size(n) {
let counter = 0
while (counter !== n) {
counter++;
}
return counter;
}
function getAt(index) {
let counter = 0;
while (counter !== index) {
counter++;
}
return counter;
}
function forEach(fn) {
const size = size(3);
for (let i = 0; i < size; i++) {
fn(getAt(i), i);
}
}
答案 0 :(得分:1)
这将是n ^ 2,因为您有一个循环,该循环将从循环i
的循环内部进行size
次调用。