[英]O(1) vs O(n) in Space Complexity
O(1)
function sum(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
function double(arr) {
let newArr = [];
for (let i=0; i<arr.length; i++) {
newArr.push(2 * arr[i]);
}
return newArr;
}
So i studying algorithm using javascript.所以我使用 javascript 研究算法。 The first one I think is O(1) because it has constant space.
我认为第一个是 O(1) 因为它有恒定的空间。 The reason why it has constant space is because number data types are constant space in javascript.
之所以有常数空间,是因为数字数据类型在 javascript 中是常数空间。 The second one makes a new array which is generally O(n) which makes its space complexity O(n).
第二个创建一个新数组,该数组通常为 O(n),其空间复杂度为 O(n)。 Am i understanding it right?
我理解正确吗?
You're mostly right, though it's not just that the second code makes a new array - you have to look at what the array contains .你是对的,虽然它不仅仅是第二个代码创建了一个新数组 - 你必须查看数组包含的内容。 Here, on every iteration, a new number is pushed to the array.
在这里,在每次迭代中,都会将一个新数字推送到数组中。 So if you have N items in the
arr
argument, you'll have N numbers in the newArr
as well.因此,如果您在
arr
参数中有 N 个项目,那么在newArr
中也将有 N 个数字。
One array * N numbers means O(n) space used.一个数组 * N 个数字意味着使用了 O(n) 空间。
If the arr
was changed to contain something else more complex, such as additional sub-arrays, the space complexity could be larger.如果将
arr
更改为包含其他更复杂的内容,例如额外的子数组,则空间复杂度可能会更大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.