Detailed explanation - Time complexity and spatial complexity

tags: javaSE  java  algorithm

Algorithm efficiency

The algorithm efficiency analysis is divided into two types: the first is time efficiency, the second is spatial efficiency. Time efficiency is called time complexity, and spatial efficiency is called spatial complexity. The time complexity is mainly measured by an algorithm running speed, and spatial complexity mainly measures the additional space required by an algorithm. In the early stage of computer development, the computer's storage capacity is small. So it is very careful to the spatial complexity. However, after the rapid development of the computer industry, the storage capacity of the computer has reached a high degree. So now we have no need to pay special attention to the spatial complexity of an algorithm.

time complexity

Let's first look at this function.

    void func1(int N){
        int count = 0;
        for (int i = 0; i < N ; i++) {
            for (int j = 0; j < N ; j++) {
                count++;
            }
        }
        for (int k = 0; k < 2 * N ; k++) {
            count++;
        }
        int M = 10;
        while ((M--) > 0) {
            count++;
        }
        System.out.println(count);
    }
  1. The first for loop needs to execute n2 times
  2. The first for loop needs to perform N * 2 times
  3. First for loop needs to be executed 10 times

So the number of executions of this FUNC method is N2 + N * 2 + 10 times

However, when we calculate time complexity, we do not have to calculate the number of exact executions, andJust need to perform the number of times, then here we use the gradual representation of large o

Big O Notation: is a mathematical symbol for describing the functionality

Detecting a large O-order method:

  1. Use constant 1 to replace all addition constants in the runtime.
  2. In the modified running function, only the highest step is retained.
  3. If the highest order exists and is not 1, the constant multiplied with this item is removed. The result is the big o order

for example

Let's take a look at a code:
This is a bubble sort code

void bubbleSort(int[] array) {
        for (int end = array.length; end > 0; end--) {
            boolean sorted = true;
            for (int i = 1; i < end; i++) {
                if (array[i - 1] > array[i]) {
                    Swap(array, i - 1, i);
                    sorted = false;
                }
            }
            if (sorted == true) {
                break;
            }
        }
    }

We can find this time efficiency

  • The array may be very fast
  • The array may be slow when it is reversed.

So we can divide it

  • Best case: o (1)
  • Worst case: o (n2)
  • Average condition: o (n)

butUnder normal circumstances, we only care about the worst situation.Because if the program can reach the target if the worst case, then there is no problem in other cases (Generally speaking time complexity is the worst case

Let's see this code again:
This is an algorithm for two-point findings. What is the complexity of this time?

    int binarySearch(int[] array, int value) {
        int begin = 0;
        int end = array.length - 1;
        while (begin <= end) {
            int mid = begin + ((end-begin) / 2);
            if (array[mid] < value)
                begin = mid + 1;
            else if (array[mid] > value)
                end = mid - 1;
            else
                return mid;
        }
        return -1;
    }


To see a hardest:
Fiboacci number:

long factorial(int N) {
    return N < 2 ? N : factorial(N-1)*N;
}

This actual is equivalent to a binary tree

Space complexity

Spatial complexity is a measure of an algorithm to temporarily occupy a storage space size during operation. The spatial complexity is not a space occupied by the program occupies, because this is not much significant, so the spatial complexity calculates the number of variables. Space complexity calculation rules are basically similar to practical complexity, but also using large O gradual representation

Example 1:

    void bubbleSort(int[] array) {
        for (int end = array.length; end > 0; end--) {
            boolean sorted = true;
            for (int i = 1; i < end; i++) {
                if (array[i - 1] > array[i]) {
                    Swap(array, i - 1, i);
                    sorted = false;
                }
            }
            if (sorted == true) {
                break;
            }
        }
    }

Example 1 A constant additional space is used, so the spatial complexity is O (1)

Example 2:

    int[] fibonacci(int n) {
        long[] fibArray = new long[n + 1];
        fibArray[0] = 0;
        fibArray[1] = 1;
        for (int i = 2; i <= n ; i++) {
            fibArray[i] = fibArray[i - 1] + fibArray [i - 2];
        }
        return fibArray;
    }

Example 2 Dynamically opened n space, spatial complexity is O (N)

Example 3:

long factorial(int N) {
    return N < 2 ? N : factorial(N-1)*N;
}

Example 3 Removing N times, open N stack frames, each stack frame uses constant space. Spatial complexity is o (n)

Intelligent Recommendation

Exception Handling in Spark Data Frames

http://anishc.me/spark/exception-handling-spark-data-frames/   Exception Handling in Spark Data Frames  7 minute read General Exception Handling Handling exceptions in imperative programming...

Python - Django Project Development: Configuration Project / Static / Path, Call CSS, IMG, JS and other static files

In Django project development, you cannot access local static files through 'Imgs / Bg.jpg' like normal web development, and you need to do some configurations to achieve access to static files. First...

Everything is an object

according totypeofThe output we can see (undefined, number, string, boolean) is a simple value type and the remaining output is aobjectThey are all reference objects. Everything (reference type) is an...

python leetcode-502-IPO

Title: IPO content: Assume that LeetCode is about to start its IPO. In order to sell shares to venture capital firms at a higher price, LeetCode hopes to launch some projects to increase its capital b...

More Recommendation

SQLALCHEMY After a period of time, there is an error in BrokenPipeError and Parent Instance <xxx at 0x ...> is not bound to a session

Error Details SQLAlChemy.exc.dbapierror: (CymySql.err.Error) (<class' brokerror ">, brokerpipeerror (32, 'broker pipe')) Well, recently used SQLalchemy, the program just started to run, eve...

Poker game -1, -2

Poker game-1 US Mei and Mountains decide to play poker cards, they have a total of N (N ≤ 100) Poker, these poker are marked as 1, 2, ... n, first, these poker is pressed The marker is placed from ...

VUEX data state persistence - Vuex-PersistedState

VUEX data state persistence - Vuex-PersistedState 1. Install Vuex-PersistedState Note: Store to LocalStorage by default using Vuex-PersistedState 2. Introduction and configuration: in Index.js under t...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top