嵌套循环的时间复杂度,无论是Big O还是Big Theta?

时间:2015-10-20 05:17:32

标签: algorithm time-complexity

package com.sss.utilities.widgets;

import android.view.View;

/**
 * @author Tom Wijgers
 */
class MeasureUtils
{
    @SuppressWarnings("unused")
    private static final String TAG = MeasureUtils.class.getName();

    public static int getMeasurement(int measureSpec, int contentSize) {
        int specMode = View.MeasureSpec.getMode(measureSpec);
        int specSize = View.MeasureSpec.getSize(measureSpec);
        int resultSize = 0;
        switch (specMode) {
            case View.MeasureSpec.UNSPECIFIED:
                //Big as we want to be
                resultSize = contentSize;
                break;
            case View.MeasureSpec.AT_MOST:
                //Big as we want to be, up to the spec
                resultSize = Math.min(contentSize, specSize);
                break;
            case View.MeasureSpec.EXACTLY:
                //Must be the spec size
                resultSize = specSize;
                break;
        }

        return resultSize;
    }
}

我知道通过查看迭代产生for (int i=1; i<n; i++) for (int j=1; j<i; j++) for (int k=j; k<n; k++) cout << "Hello world" << endl; 的次数来获得时间复杂度。我对时间复杂度是否为O(n 3 )或Θ(n 3 )感到困惑?

2 个答案:

答案 0 :(得分:1)

Big O符号表示最坏情况&#34;。在这里你没有最坏的情况,你循环特定的次数。 Theta表示上限和下限,由于这两者在您的场景中相同,因此它是Theta。

答案 1 :(得分:0)

两者兼而有之。 Big O为您提供运行时的上限,而Big Theta为您提供上限和下限。 如果函数在Big Theta中表示,那么它包括Big O和Big Omega。 在数学上,

if f(n)=O(g(n)) then 0<=f(n)<=Cg(n) for any positive constant C.

if f(n)=Theta(g(n)) then c1g(n)<=f(n)<=c2g(n) for any positive constants c1 and c2.

在你的问题中,运行时是n中的三次多项式,多项式函数可以用它在n中的最高幂来表示。

因此Big O(n^3)Big Theta(n^3)以及Big Omega(n^3)都是。

相关问题