问题
I'm currently working on a project for school in which I have a time complexity restriction. I'm still beginning to learn to program so apologies of this question is stupid.
Essentially, let's say I have a constraint that my program must satisfy the time complexityO(n2 + m log m)
, where n
and m
are some sizes of input. Does that mean that's the maximum time complexity any specific component of my program can run in? That is, if I have a ton of, say, O(n2 + m)
functions, but the most complex function runs in O(n2 + m log m)
, will I still satisfy this time bound?
For example, if my program runs the functions A
, B
, C
, and D
in order,
and functions A
, B
, C
are all O(n2 + m)
or something less than that time complexity restraint, but the last function D
is O(n2 + m log m)
, will my program be within the time constraint?
Would that not somehow be O(n2 + mn2 + mn2 + m + n2 + m log m)
for the overall complexity?
I'm still learning about time complexity, so any help for this would be much appreciated. Thanks a bunch.
回答1:
If you're executing different functions in sequence, you just choose the worst complexity and that's the overall complexity.
For example, if fnA
was O(n)
and fnB
was O(nn!)
, then any effect of fnA
would be totally swamped by fnB
, assuming they're run sequentially (not nested).
In your case, the final of your functions meet the requirement and the first three are better, so the overall complexity is that of the final one.
来源:https://stackoverflow.com/questions/65045203/additivity-of-time-complexity