### 了解两个嵌套while循环的时间复杂度

#### [英]Understanding time complexity of two nested while loop

The following block of code is from a function that finds the minimum number of coins required to achieve a certain amount given by the user. Here two queue "sums" and "costs" are used.

``````while(Sums.front()<=TargetSum){
int tempSum = Sums.front();
Sums.pop();
int tempCost = Costs.front();
Costs.pop();

for(int i=0;i<TypesOfCoins;i++)
{
Sums.push(coins[i]+tempSum);
Costs.push(tempCost+1);
if(Sums.back()==TargetSum)
{
cout<<"Sums:"; DisplayQueue(Sums);
cout<<"Cost:"; DisplayQueue(Costs);
return Costs.back();
}
}
}
``````

As far as I know, for nested loops times complexity is the numbers of times innermost loop iterates, so time complexity for this loop should be O(n^2), shouldn't it?

## 1 个解决方案

### #1

1

The two examples below have the same complexity even that `n` is different. And their complexity, or Big-O, is O(InputData * 1) which is O(InputData):

``````int n = 10;
FuncA(int InputData)
{
for(int i = 0; i < n; i++) // n is outer loop.
{
for(int j = 0; j < InputData; j++)
{
// .. do stuff
}
}
}
``````

Or

``````int n = 100000000;
FuncB(int InputData)
{
for(int i = 0; i < InputData; i++)
{
for(int j = 0; j < n; j++) // n is inner loop
{
// .. do stuff
}
}
}
``````

`n` is a constant, and that means any loop that depends on `n` has O(1) complexity.

n是常量，这意味着任何依赖于n的循环都具有O（1）复杂度。

`InputData` is not constant, and that means any loop that depends on `InputData` has O(InputData) complexity.

InputData不是常量，这意味着任何依赖于InputData的循环都具有O（InputData）复杂性。

Total Complexity = Complexity of all loops => O(InputData * 1)

Note that "Time To Finish" for both functions is different (since `n` is bigger, hardware speed.. etc). But the "Computation Complexity" is the same: No matter which loop is the inner loop nor how big is the constant (`n` in this case).

Edit:

A nice idea: if you have a problem and you KNOW how to solve it, but it just requires 10 years of time. Would that be complex?

The answer is no, it is not complex. It is simple but just requires time. (`n` in my example is times to process something, but the process has no complexity, it is just repeated for a constant amount of time).