【发布时间】:2021-06-03 10:24:21
【问题描述】:
我正在学习数据结构,对这个游戏很陌生。我知道为 n 次迭代运行的单个循环具有 O(n) 时间复杂度。但是如果我在 for 循环中使用splice,它会是 O(n2) 时间复杂度吗?我很肯定它是 O(n2) 但想确定一下。
这是我正在处理的示例代码:
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
};
【问题讨论】:
-
对
.splice()的调用基本上是一个“隐藏循环”,所以是的,我称之为n² -
虽然
splice可能是一个“隐藏循环”,因为您一次只使用它添加一个元素,您可以获得的最差性能是在第一个位置添加每个新元素(又名unshift),从而将所有其他元素向上移动一个索引。我不确定unshift的时间复杂度是多少,所以我会留给你/其他人去寻找。
标签: javascript algorithm data-structures