Complexity of time and space

Source: Internet
Author: User

Complexity of Time

The simple understanding of time complexity is the number of lines that execute the statement. If there are loops and recursion, the simple statement is ignored, and the number of statements executed by the loop and recursion is calculated directly.

Like what:

[Java]View PlainCopy
    1. int x = 1; Time Complexity of O (1)
    2. for (int i=0; i<n; i++) {
    3. System.out.println (i);
    4. }//Time complexity of O (n)

Specific examples:

1, O (1)

[Java]View PlainCopy
    1. int x = 1;


2, O (n)

[Java]View PlainCopy
    1. for (int i=0; i<n; i++) {
    2. System.out.println (i);
    3. }


3. O ()

[HTML]View PlainCopy
    1. int n = 8, count = 0;;
    2. for (int i=1; I<=n; i *= 2) {
    3. count++;
    4. }


4.

[HTML]View PlainCopy
    1. int n = 8, count = 0;;
    2. for (int i=1; I<=n; i++) {
    3. for (int j=1; J<=n; J + +) {
    4. count++;
    5. }
    6. }


5.

[Java]View PlainCopy
    1. int n = 8, count = 0;;
    2. for (int i=1; i<=n; i *= 2) {
    3. For (int j=1; j<=n; J + +) {
    4. count++;
    5. }
    6. }


The examples are relatively simple.

Complexity of space

Spatial complexity is also a simple understanding of the storage space occupied by temporary variables. A simple example:

[Java]View PlainCopy
    1. Swap two variables x and y
    2. int x=1, y=2;
    3. int temp = x;
    4. x = y;
    5. y = temp;

A temporary variable temp, so the spatial complexity is O (1).

Transferred from: http://blog.csdn.net/qiantujava/article/details/12898461

Time complexity and spatial complexity (RPM)

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.