Two time complexity and space complexity

Source: Internet
Author: User

Complexity of Time:

1 Find the basic statement: the most executed statement in the algorithm is the basic statement, usually the most inner loop of many loops.

2 Calculate the order of magnitude of the base statement:

You only need to calculate the number of executions of the base statement. Ensure that the highest power is correct.

Ignore the coefficients of the lower power and the highest power, simplify the analysis, and focus on the most important point: growth rate.

3 The performance of the algorithm is represented by the large O notation.

The number of algorithms for basic statement executions is placed in the large O-notation.

Example:

    • The time complexity of a simple statement is O (1)
    • The time complexity of a loop is O (n)

for (int i = 1; i <=n; i++) {count++}

    • The time complexity is O (log2 N) loop statement, the efficiency is particularly high

for (int i = 1; i <=n; i*=2) {count++}

1 2 4 8 16 32 2^30 = 1024*1024*1024=1000*1000*1000=10 billion i*=2 O (log 2 1 billion) 30 times, i++ O (1 billion) cycle required 1 billion times, log 2 n efficiency >> ; n

    • A double cycle with a time complexity of O (n^2)

for (int i = 1; i <=n; i++)

for (int j = 1; j<=i; j + +)

count++;

    • The time complexity is O (nlog2 N) of the double cycle:

for (int i = 1; i <=n; i*=2)

for (int j = 1; j<=n; j + +)

count++; Inner Loop n times, outer loop log2 n times, O (n*log2 N)

    • The time complexity is O (N2) of the double cycle:

for (int i = 1; i <=n; i++)

for (int j = 1; j<=i; j + +)

count++; Outer Loop n times, Inner loop indeterminate t (n) = 1+2+3+4+......+n= (1+n) n/2,o (n^2)

Spatial complexity (space):

See the number of variables. Generally speaking is S (1).

Recursive algorithm each call itself to allocate space, space complexity is higher.

Advantages and disadvantages of recursion: inefficient, occupy more space. Simple code, simple thinking.

Two time complexity and space complexity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.