I was thinking the complexity would be O(n^2). Am I wrong? If so, could you please explain why?
public int countXs(char[][] m)
{
int rows = m.length, cols = m[0].length;
int r = 0, c = 0, count = 0;
while (r < rows || c < cols)
{
count += r;
while (r < rows && m[r][c] == 'x')
{
count++;
r++;
}
c++;
}
return count;
}
Firstly, your code may crash because of arrayIndexOutofBound
with c
index.
Next, when you invest the time complexity, firstly, you need to define what is n
. Normally n
indicates the size of input, in this case n
is the size of 2-dimensional array.
So, you need setup the formula to time complexity and specify the worst case of your code to find time complexity. Suppose that array m
is pxq (p + q = n)
and we denote O(1) = 1
.
T(n) = Sum(i->max(p, q)) {1 + sum(j->p)(1)}
= max(p,q) + sum(i->max(p,q)){p}
= max(p, n-p) + sum(i-> max(p, n-p)) {p}
= max(p, n-p) + p(n-p)
Based on Cauchy inequality :
4*ab <= (a+b)^2 we have: p(n - p) < (p + n - p)^2 /4 = n^2/4
So:
T(n) <= n + n^2/4 = O(n^2) . Q.E.D
Read more: http://en.wikipedia.org/wiki/Time_complexity
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.