Determining the complexities given codes

前端 未结 6 441
天涯浪人
天涯浪人 2021-01-30 11:19

Given a snipplet of code, how will you determine the complexities in general. I find myself getting very confused with Big O questions. For example, a very simple question:

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 11:36

    For the first snippet, it's just n^2 because you perform n operations n times. If j was initialized to i, or went up to i, the explanation you posted would be more appropriate but as it stands it is not.

    For the second snippet, you can easily see that half of the time the first one will be executed, and the second will be executed the other half of the time. Depending on what's in there (hopefully it's dependent on n), you can rewrite the equation as a recursive one.

    The recursive equations (including the third snippet) can be written as such: the third one would appear as

    T(n) = T(n-1) + 1
    

    Which we can easily see is O(n).

提交回复
热议问题