简体   繁体   English

此算法是O(1)还是O(n)空间复杂度

[英]Will this algorithm be O(1) or O(n) space complexity

I have a homework question that is asking me to find a missing number in an array with an O(n) time complexity and O(1) space complexity program. 我有一个作业问题,要求我在具有O(n)时间复杂度和O(1)空间复杂度程序的数组中找到缺失的数字。

I feel like I have a pretty good grasp of what constitutes O(1) space complexity, however I am unsure of whether assigning a variable to be the largest value in the given array would make it O(n) space complexity. 我觉得我对O(1)空间复杂度的构成有了很好的了解,但是我不确定将变量分配为给定数组中的最大值是否会使其成为O(n)空间复杂度。 The code below is what I have written specifically 下面的代码是我专门写的

def findMissing(A):
    greatest = 0
    for i in range(len(A)):
        if A[i] > greatest:
            greatest = A[i]

I am thinking it would still be O(1) because the O(n) that I am trying to stay under is the full array containing the greatest value as well as all the other values, but at the same time my variable is still related to the input size, so I am unsure. 我想它仍然是O(1),因为我要停留在的O(n)是包含最大值以及所有其他值的完整数组,但是与此同时,我的变量仍然相关输入的大小,所以我不确定。

Since your code loops through the array once, it has O(n) time complexity. 由于您的代码循环遍历数组一次,因此具有O(n)的时间复杂度。 Storage only maintains 1 variable so it has O(1) space complexity. 存储仅维护1个变量,因此具有O(1)空间复杂度。 I'm assuming you left off the return statement for the sake of the question, otherwise, be sure you include that too. 我假设您出于问题的考虑而放弃了return语句,否则,请确保也将其包括在内。

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

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