该算法最坏情况的时间复杂度是多少?

时间:2020-06-10 15:52:57

标签: python-3.x algorithm time-complexity complexity-theory

我正在分析一种算法,该算法给出方阵的“峰值”的位置(这意味着该值的邻居小于或等于该值)。 有问题的算法效率很低,因为它会从位置(0,0)开始移动到大于该数字的邻居,从而一一检查值。这是代码:

def algorithm(problem, location = (0, 0), trace = None):
    # if it's empty, it's done!
    if problem.numRow <= 0 or problem.numCol <= 0:                                  #O(1)
        return None

    nextLocation = problem.getBetterNeighbor(location, trace)                       #O(1)
    #This evaluates the neighbor values and returns the highest value. If it doesn't have a better neighbor, it return itself

    if nextLocation == location:
        # If it doesnt have a better neighbor, then its a peak.
        if not trace is None: trace.foundPeak(location)                             #O(1)
        return location
    else:
        #there is a better neighbor, go to the neighbor and do a recursive call with that location
        return algorithm(problem, nextLocation, trace)                             #O(????)

我知道最好的情况是峰值位于(0,0),并且确定以下情况是最坏的情况(使用10x10矩阵):

problem = [
 [0,   1,  2,  3,  4,  5,  6,  7,  8,  9],
 [0,   0,  0,  0,  0,  0,  0,  0,  0, 10],
 [34, 35, 36, 37, 38, 39, 40, 41,  0, 11],
 [33,  0,  0,  0,  0,  0,  0, 42,  0, 12],
 [32,  0, 54, 55, 56, 57,  0, 43,  0, 13],
 [31,  0, 53,  0,  0, 58,  0, 44,  0, 14],
 [30,  0, 52,  0,  0,  0,  0, 45,  0, 15],
 [29,  0, 51, 50, 49, 48, 47, 46,  0, 16],
 [28,  0,  0,  0,  0,  0,  0,  0,  0, 17],
 [27, 26, 25, 24, 23, 22, 21, 20, 19, 18]]

请注意,它基本上使算法呈螺旋状运行,并且必须评估59个位置。

因此,问题是:在这种情况下,我如何获得时间复杂度?为什么? 我知道除递归外所有操作都是O(1),我迷路了

1 个答案:

答案 0 :(得分:1)

对于您在示例中显示的大小为[m,n],的任意矩阵,我们可以按以下方式分解由该算法(A)生成的给定矩阵的遍历:

  • A将从左上角遍历n-1个元素到元素8,
  • 然后将m-1个元素从9改为17,
  • 然后从18到27的n-1个元素,
  • 然后将m-3元素从27改为33,
  • 然后将n-3个元素从34个增加到40个,
  • 然后将m-5个元素从41改为45,
  • 然后将n-5个元素从46变为50,
  • 然后从51到53的m-7个元素

这时,模式应该很清楚,因此可以建立以下最坏情况的重复关系:

    T(m,n) = T(m-2,n-2) + m-1 + n-1
    T(m,n) = T(m-4,n-4) + m-3 + n-3 + m-1 + n-1
    ...
    T(m,n) = T(m-2i,n-2i) + i*m + i*n -2*(i^2)

其中i是迭代次数,并且仅当m-2in-2i都大于0时,这种重复才会继续。

WLOG我们可以假设m>=n,因此该算法在m-2i>0m>2i或im / 2迭代期间继续。因此,为i重新插入,我们得到:

    T(m,n) = T(m-m,n-m) + m/2*m + m/2*n -2*((m/2)^2)
    T(m,n) = 0 + m^2/2 + m*n/2 -2*((m^2/4))
    T(m,n) = 0 + m^2/2 + m*n/2 -2*((m^2/4))
    T(m,n) = m*n/2 = O(m*n)