简体   繁体   English

如何更改算法以获得更好的渐近复杂度?

[英]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: 这是时间:

  • real 0m0.164s 真正的0m0.164s
  • user 0m0.021s 用户0m0.021s
  • sys 0m0.010s sys 0m0.010s

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.

相关问题 获得更好的时间复杂度 - Get Better Time Complexity 我怎样才能更有效地编写这个算法? 以降低时间复杂度的方式? - how can i write this algorithm more efficiently ? in a way that reduce time complexity? 如何找到这个算法的复杂度? - How to find the complexity of this algorithm? 该算法的空间复杂度如何为O(1) - How the space complexity of this algorithm is O(1) 有没有更好的方法来提高一个对象中包含多个数组的算法的复杂性 - Is there a better way to improve the complexity of a algorithm that includes multiple arrays in an object 如何从该Java程序中获取解决算法的解决方案? - How can I get a solution from this Java Program to solve algorithm? 如何在不改变原始数组的情况下从时间复杂度为 O(n) 或更好的排序数组中获取唯一值 - How to get unique values from a sorted array with time complexity of O(n) or better without altering the original array 如何找到给定算法的比较次数和复杂度 - How to find number of comparisons and complexity of a given algorithm 如何确定以下程序的时间和空间复杂度? - How can I determine Time and Space Complexity of the below program? 如何改进这种排序算法? - How can I improve this sorting algorithm?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM