对于以下代码的“大哦”感到困惑:
iOS 5
是O(n ^ 2)吗?使我感到困惑的部分是j = i以及它将如何影响运行时。
答案 0 :(得分:0)
是的,它是O((array.length)^ 2)。
答案 1 :(得分:0)
假设 array.length 为 n ,则内部循环的总执行量为:
round 1 (i=0) : n this round j = 0 to n-1
round 2 (i=1) : n-1 this round j = 1 to n-1
.
.
.
round n (i=n-1) : 1 this round j = n-1 to n-1
--------------------------------
Total : n*(n+1)/2 is in O(n^2)
1+ 2+ ... + n = n(n + 1)/ 2 wikipedia link