0
說我有兩個已排序的列表如下所示:找到最大的最大總和,兼容,在子二次時間兩個已排序的陣列的值
- A = [13,7,5,3,2, ...,0]
- b = [16,12,8,4,...,1]
另外我有一個函數:
IsValid(x,y):
如果x返回true和y是compat IBLE。兼容性完全是任意的,除了值0對任何其他數字都有效。
因此,如何找到a和b中的兩個數字,以便產生最大的總和,因爲它們都是IsValid。即找到最大的有效總和。
這裏是用Python
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
不,但謝謝您的輸入。 是啊它的可能最壞的情況O(n^2)。 在這種情況下,我相信我的alg產生的速度很快,但可能不合格的結果,這是可以接受的。 – hoshi