简体   繁体   English

时间/空间复杂性 - 如何弄清楚这个功能?

[英]Time/Space Complexity - How to figure out in this function?

I need to calculate the time and space complexity for this problem, can anyone help me figure out what it is and why? 我需要计算这个问题的时间和空间复杂度,任何人都可以帮我弄清楚它是什么以及为什么?

I believe the time complexity for this problem would be O(n^2) because of the 2 filter functions. 我相信这个问题的时间复杂度将是O(n ^ 2),因为2个滤波器函数。 Essentially, it would be similar to having 2 for-loops that iterate over the array and because they are looping for a set amount of time, we know that it will be O(n) for the first filter and adding another would make it O(n^2)? 本质上,它类似于有2个for循环遍历数组并且因为它们循环了一段时间,我们知道它将是第一个过滤器的O(n)并且添加另一个将使它成为O (N ^ 2)?

Not sure about space complexity. 不确定空间复杂性。

let arr = [1, 2, 2, 4, 4, 5, 6, 7, 7, 8, 9];
const result = arr.filter(x => arr.filter(y => y === x).length > 1)
console.log(result);
// 2, 2, 4, 4, 7, 7

Yes, time complexity is O(n^2) - for example, if arr has 10 items, the algorithm needs to make ~100 comparisons before finishing. 是的,时间复杂度为O(n^2) - 例如,如果arr有10个项目,算法需要在完成之前进行~100次比较。

Space complexity is O(n) . 空间复杂度为O(n) For example, consider the last iteration of the outer .filter - the result that's almost finished being constructed takes up O(n) space at that time (worst-case; equivalent to the side of the input arr ). 例如,考虑外部.filter的最后一次迭代 - 几乎完成构造的result那时占用O(n)空间(最坏情况;相当于输入arr的一侧)。 The inner array inside the callback being filtered (which will then have its length checked, and returned) will also be, worst-case, the side of the input n . 被过滤的回调内部的内部数组(其将检查并返回其length )也将是最坏情况下输入n的一侧。 So, the most space that will be being currently used at any point in time is O(2n) , which is equivalent to O(n) . 因此,目前在任何时间点使用的最大空间是O(2n) ,相当于O(n)

I think you are right about the time complexity, it is O(n^2) due to the two nested loops. 我认为你对时间复杂度是正确的,由于两个嵌套循环,它是O(n ^ 2)。

IMO space complexity is O(n) as you need only n units of space to keep the array and no additional memory is allocated. IMO空间复杂度为O(n),因为您只需要n个单位的空间来保留阵列,并且不会分配额外的内存。

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

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