简体   繁体   English

空间复杂度中的 O(1) 与 O(n)

[英]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.

相关问题 这个算法的时间和空间复杂度是 O(n) 还是 O(1)? - Does this algorithm have time and space complexity O(n) or O(1)? 以下代码片段的空间复杂度是 O(1) 还是 O(N)? - Is the space complexity O(1) or O(N) for the following code snippet? 该函数的时间复杂度是O(N)还是O(N ^ 2)? - Is the time complexity for this function O(N) or O(N^2)? Javascript - 在时间复杂度为 O(n) 且空间复杂度为 O(1) 的给定字符串中删除交替重复字符的最佳方法是什么? - Javascript - What is the best way to remove alternate repeating character in a given string with time complexity O(n) and Space Complexity was O(1)? 此解决方案O(N)或O(LogN)的时间复杂度是多少? - What is time complexity of this solution O(N) or O(LogN)? 简化O(nm)和O(n + m)时间复杂度 - Simplifying O(nm) and O(n + m) time complexity 反转空间复杂度为 o(1) 的句子中的单词 - Reverse words in a sentence with space complexity o(1) 这个函数的时间复杂度是否为O(log n)? - Is the time complexity of this function O(log n)? 这个O(1)空间怎么样而不是O(n)空间。 firstNotRepeatingCharacter挑战解决方案 - How is this O(1) space and not O(n) space. firstNotRepeatingCharacter Challenge solution 我对最小差分算法问题的解决方案是否具有最佳时空复杂度 (O(nLog(n) + mLog(m)))? - Does my solution to the Smallest Difference algorithm problem have optimal space time complexity (O(nLog(n) + mLog(m)))?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM