[英]How i can change algorithm to get better asymptotic complexity?
guys. 伙计们
I have an algo with a good timing, i should change it to get better time, but i have no any idea. 我有一个时机很好的算法,我应该更改它以获得更好的时间,但是我不知道。
Can u help me? 你能帮我吗?
Here is time: 这是时间:
Here is algo: 这是算法:
def algo2(A, B):
x=0
y=0
for a in A:
m=0
for b in B:
if a == b:
m += 1
if m>y:
x = a
y = m
return x;
Here is arrays for algo: 这是算法数组:
A = [1,2,3,4,5,6,7,8,9,0] B = [1,2,3,4,5,6,4,7,8,9,0] A = [1,2,3,4,5,6,7,8,9,0] B = [1,2,3,4,5,6,4,7,8,9,0]
Your algorithm is O(n*m). 您的算法为O(n * m)。 If the arrays are always sorted, you can do a straight merge (O(n+m)), as below. 如果始终对数组进行排序,则可以进行直接合并(O(n + m)),如下所示。 (Note that the code is not python ... I think you can get the idea and translate it) (请注意,代码不是python ...我想您可以理解并翻译它)
ixA = 0
ixB = 0
maxVal = 0
maxCount = 0
workingVal = A[ixA]
workingCount = 0
while (ixA < A.length and ixB < B.length)
{
if (workingVal == B[ixB])
{
workingCount += 1
}
else if (workingCount > maxCount)
{
maxCount = workingCount
maxVal = workingVal
workingCount = 0
ixA += 1
workingVal = A[ixA]
}
ixB += 1
}
// have to check the last one
if (workingCount > maxCount)
{
maxCount = workingCount
maxVal = workingVal
}
If the arrays aren't sorted, you can sort them first, then do the merge. 如果未对数组进行排序,则可以先对其进行排序,然后再进行合并。 That will be O(m log m) + O(n log n) + O(m+n). 这将是O(m log m)+ O(n log n)+ O(m + n)。 That's still better than your O(m*n). 那仍然比您的O(m * n)好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.