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).
A simple example of an algorithm O(m+n):
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)
nArr
n
mArr
m
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(), . , .
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 . ( ), , .
, , , :
, 2 O (M + N), O (N) ( , N > M) O (M) ( M > N).
, - , , M N . O (M + N).
.
, n m. , , .
O (n) (.. BIG-O), , . , O(n) = n^2. O (n) n^2, n () .
O(n) = n^2
n^2
, m . O(m) m^2. , O(m) = m. linear.
O(m)
m^2
O(m) = m
, O(n+m), n^2? . n=m, 2n 2m. - , - n m. O(n+m) = n+m.
O(n+m)
n=m
2n
2m
O(n+m) = n+m