O (N + M) time complexity

I work on some practical problems when they ask me the complexity of time and complexity. One of them gives the target time complexity of O (N + M). I am having problems with the intuition of what the O (N + M) algorithm will look like. Does anyone have an example of such an algorithm or can they explain it clearly? Every example I try to present seems to me O (N * M).

+4
source share
5 answers

A simple example of an algorithm O(m+n):

int sum(int[] nArr, int[] mArr) {
    int sum = 0;
    for(int i : nArr) {
        sum += i;
    }
    for(int i : mArr) {
        sum += i;
    }
    return sum;
}

To calculate the sum, you need to go through all the elements in nArr(size n) and all the elements in mArr(size m), so the overall complexityO(m+n)

+11

O (n + m):

for (i = 0; i < n; i++)
{
  // do something but don't loop or invoke recursive functions
  // only constant O(c) complexity is allowed: a simple series of commands
}

for (i = 0; i < m; i++)
{
  // idem
}

(O (n + m) == O (m + n)), , for(), . , .

, O (n * m):

for (i = 0; i < n; i++)
{
  for (j = 0; j < m; j++)
  {
    // do something but don't loop or invoke recursive functions
    // only constant O(c) complexity is allowed: a simple series of commands
  }
}

, , (O (n * m) == O (m * n)). .

, for(), , o . ( ), , .

+5

, , , :

  • / N , M. min/max, .

, 2 O (M + N), O (N) ( , N > M) O (M) ( M > N).

+1

, - , , M N . O (M + N).

.

0

, n m. , , .

O (n) (.. BIG-O), , . , O(n) = n^2. O (n) n^2, n () .

, m . O(m) m^2. , O(m) = m. linear.


, O(n+m), n^2? . n=m, 2n 2m. - , - n m. O(n+m) = n+m.

-1

All Articles