[英]Space complexity of algo
Is the space complexity of this function N^2 as the output is a linked list?这个函数的空间复杂度是 N^2,因为输出是一个链表?
I am learning about space complexity in school and am stuck on this question.我正在学校学习空间复杂性,并被困在这个问题上。
def myHealthcare(record):
l2=[]
count=0 # num of records generated and the specific time
for i in range(record):
l=[]
now = datetime.datetime.now()
ts = now.strftime("%d/%m/%Y %H:%M:%S") # str timestamp
ts=ts +' '+str(count)
l.append(ts)
l.append(rand.randint(36,39)) #temp
l.append(rand.randint(55,100)) #hr
l.append(rand.randint(55,100)) #Pulse
l.append(rand.randint(120,121)) #bp
l.append(rand.randint(11,17)) #respiratory rate
l.append(rand.randint(93,100)) #oxygen sat
l.append(round(rand.uniform(7.1,7.6),1)) #pH
l2.append(l)
count+=1
return l2
The space complexity of a linked list is not quadratic;链表的空间复杂度不是二次的; each linked list node takes a constant amount of auxiliary memory, so the auxiliary memory used by the whole data structure is O( n ) where n is the number of nodes.每个链表节点占用固定数量的辅助内存,因此整个数据结构使用的辅助内存为O( n ),其中n为节点数。
However, you are also constructing strings and storing these in memory.但是,您也在构建字符串并将它们存储在内存中。 The string str(count)
is part of a string that gets appended to your list l
on each iteration, and the length of this string is O(log n ) since count
is a number up to n , and it has O(log n ) digits when represented as a string.字符串str(count)
是在每次迭代时附加到列表l
的字符串的一部分,并且该字符串的长度是 O(log n ) 因为count
是一个直到n的数字,并且它有 O(log n ) 表示为字符串时的数字。 So the overall space complexity of this algorithm is O( n log n ) because of that.因此,该算法的整体空间复杂度为 O( n log n )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.