找到子二次时间中两个排序数组的最大,兼容值的最大和

时间:2014-06-20 17:16:34

标签: python algorithm sorting

说我有两个排序列表如下:

  • a = [13,7,5,3,2,...,0]
  • b = [16,12,8,4,...,1]

我也有一个功能:

IsValid(x,y):

如果x和y兼容,则返回true。兼容性完全是任意的,除了值0对任何其他数字有效。

那么我怎样才能找到a和b中的两个数字,因为它们都是IsValid,所以得到最大的数。即找到最有效的总和。

这是我目前在Python中的alg

def FindBest(a, b):
isDone = False
aChecked =[]
bChecked = []
aPossible = []
aIndex = 0
bPossible = []
bIndex = 0
posResult = []



#initialize
try:
    aPossible= (a[aIndex])
    aIndex+=1
    bPossible=(b[bIndex])
    bIndex+=1
except:
    print "Why did you run this on an empty list?"
    return

while not isDone:
    posResult = []


    if(len(aPossible)>0):
        for b in bChecked:
            if(IsValid(aPossible,b)):
                posResult.append(aPossible+b)
                isDone = True


    if len(bPossible)>0:
        for a in aChecked:
            if(IsValid(a,bPossible)):
                posResult.append(a+bPossible)
                isDone = True

    #compare the first two possibles
    if(IsValid(aPossible,bPossible)):
                posResult.append(aPossible+bPossible)
                isDone = True

    if(len(aPossible) > 0):
        aChecked.append(bPossible)
    if(len(bPossible) >0):
        bChecked.append(bPossible)

    if(aIndex<len(a)):
        aPossible= (a[aIndex])
        aIndex+=1
    if(bIndex<len(b)):
        bPossible =(b[bIndex])
        bIndex+=1
    if len(a)==len(aChecked) and len(b) == len(bChecked):
        print "none found"
        isDone = True

return posResult

1 个答案:

答案 0 :(得分:1)

但正如其他人所指出的,最糟糕的情况是O(n*n),其中n是每个列表的大小。

对于最糟糕的情况示例,请考虑除a = [9,8,7,0]以外没有兼容对的b = [4,3,2,1](0,4),(0,3),(0,2),(0,1)

让我们乐观地假设您以某种方式检查并首先找到这四对。 所以你记得那对(0,4)是目前最好的答案。 您仍然需要检查所有大于4的对,以确保(0,4)确实是最佳答案。 列出这些对:

(9,4)
(9,3) (8,4)
(9,2) (8,3) (7,4)
(9,1) (8,2) (7,3)

这些对的数量正在增长O(n * n)。

因此不可能推导出 sub 二次时间算法。 [因为我假设可以实现最好的算法,在某些情况下该算法仍然至少需要O(n * n)]

也许您从问题中遗漏了更多信息?