请允许我说,为了从名单上获得最大分类,我可以采用以下两种方法:
1)
x = max(arr)
b)
x = 0
for ele in arr:
x = max(x,ele)
我现在想知道,每种方法的绩效如何? 以及哪一个更快? 时间和空间的复杂性是什么? 谁喜欢?
额外<代码>max(x, ele)比<代码>max(r)更复杂时间的比较? 或反之亦然?
================================================================================================================================================================================================================================================================
edited 8/26/23 now everyone says first one is faster, how about in the example below ?
given a list arr = [1,6,0,9,3,12,8,5]
, I wanna make a new list from all elements inside arr that the elements can divide by 3, and keep track of the max element in it.
1)
newArr = []
for ele in arr:
if ele%3 == 0:
newArr.append(ele)
x = max(newArr) #now newArr should be [6,0,9,3,12]
b)
newArr = []
x = 0
for ele in arr:
if ele%3 == 0:
newArr.append(ele)
if ele > x: #would x = max(x, ele) cause more time complexity ?
x = ele
如今,在这种例子中,第2条办法是否不太复杂,因为它只是一次重复使用,而比较了吗? 由于O(n)越高,第1条办法是否更复杂?
I did the test like @KellyBundy did, seems like if ele > x: x = ele
is way faster than x = max(x, ele)
, and little bit faster than max(newArr)
, see result below.
另一项测试也采用了宽松清单,这一次最大程度要快得多。
但是,当我与另一个汇编者一起工作时,结果并没有大不相同,令人非常感兴趣的是我利用方案在线汇编者汇编的法典。