了解两个嵌套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?

据我所知,对于嵌套循环,时间复杂度是最内层循环迭代的次数,因此这个循环的时间复杂度应该是O(n ^ 2),不是吗?

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):

下面的两个例子具有相同的复杂性,即使n是不同的。它们的复杂性或Big-O是O(InputData * 1),它是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)

总复杂度=所有循环的复杂性=> 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).

请注意,两个函数的“Time To Finish”是不同的(因为n更大,硬件速度等等)。但是“计算复杂性”是相同的:无论哪个循环是内循环,也不是常数有多大(在这种情况下为n)。

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?

一个好主意:如果你有问题并且你知道如何解决它,但它只需要10年的时间。这会很复杂吗?

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).

答案是否定的,并不复杂。这很简单但只需要时间。 (在我的例子中,n是处理某些东西的时候,但是这个过程没有复杂性,只是重复了一段时间)。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2017/07/14/a3a5cd5b98f8e5a748b23caa1fa8058e.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告