问题
int fun(int n) {
int count = 0;
for (int i = n; i > 0; i /= 2)
for (int j = 0; j < i; j++)
count += 1;
return count;
}
I'm a very new to the time complexities calculations. For this algorithm, I get the answer to be O(nlogn), but the answer is apparently O(n).
My logic was the outer loop has an exponential decline and will occur log_base2_(N) times. The inner loop will run a total of N times as it becomes a geometric sum (first iteration it is N/2 times, then N/4, then N/8 ...). If I put these together and multiply them as a result of the nested loop, that's where I'm coming up with O(NlogN). Am I missing something obvious?
回答1:
The outer loop would run a total of log(n) times. Now if you observe the inner loop it first time it runs n times, next n/2 times and so on, so it makes the series
n(1 + 1/2 + 1/4 + 1/8 + 1/16 + ...)
the sum of this would be (2*n), That means it is O(n)
Hence the time complexity is O(n) since outer loop runs O(logn) times and inner loop runs O(n) times.
It is not O(nlogn) since the inner loop does not take n steps each time, in fact the sum of all steps taken would be O(n)
来源:https://stackoverflow.com/questions/46195687/algorithm-time-complexity-i-2-in-loops