简体   繁体   English

简单function的大O

[英]Big O of a simple function

I am learning data structure and pretty new to this game.我正在学习数据结构,并且对这个游戏很陌生。 I know a single loop running for n-iteration has O(n) time complexity.我知道为 n 次迭代运行的单个循环具有 O(n) 时间复杂度。 But if I use a splice inside the for loop, is it going to be O(n 2 ) time complexity?但是如果我在 for 循环中使用splice ,它会是 O(n 2 ) 时间复杂度吗? I am positive it's O(n 2 ) but want to make sure.我很肯定它是 O(n 2 ) 但想确定一下。

Here is the sample code that I was working on:这是我正在处理的示例代码:

var createTargetArray = function(nums, index) {
    let target = []
    for (let i=0; i< index.length; i++){
        let idx = index[i]
        target.splice(idx,0,nums[i])
    }
    return target
};

You are correct.你是对的。 Worst case for the splice method should be O(n).拼接方法的最坏情况应该是 O(n)。 That call is occuring inside the iteration of a foreach loop O(n);该调用发生在 foreach 循环 O(n) 的迭代中; So the big o-notation of the whole script is O(n^2)所以整个脚本的大 o-notation 是 O(n^2)

Since big O notation is asking how many iterations your function takes to perform f(x) to your array as input, when you loop over all the elements the general time complexity of O(n).由于大 O 表示法询问您的 function 需要多少次迭代才能对数组执行 f(x) 作为输入,所以当您遍历所有元素时,一般时间复杂度为 O(n)。 However using the.splice() function in JavaScript also has ideally a time complexity of O(n) and thus when you put a O(n) in another O(n) then it effectively becomes O(n^2).然而,在 JavaScript 中使用 .splice() function 也具有理想的 O(n) 时间复杂度,因此当您将 O(n) 放入另一个 O(n) 时,它实际上变为 O(n^2)。 As a good rule of thumb you can think of nested O(n) increasing the power of n by one.作为一个好的经验法则,您可以考虑嵌套 O(n) 将 n 的幂增加一。 For example if you were to loop to have a triple nested loop doing 1 operation to each element of an array it would become O(n^3) and so on.例如,如果您要循环让一个三重嵌套循环对数组的每个元素执行 1 次操作,它将变为 O(n^3) 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM