简体   繁体   English

计算迭代算法的时间复杂度

[英]Calculating time complexity of a Iterative algorithm

I am dealing with a problem where two singly linked list merge at some point. 我正在处理两个单链列表在某个时刻合并的问题。 Following image illustrates this concept. 下图说明了此概念。

在此处输入图片说明

I am suppose to find and return the node where they both intersect. 我想找到并返回它们都相交的节点。 I am only given the reference to head of both lists. 我只提到两个列表的头。 Following is the algorithm i came up with. 以下是我想出的算法。

public Node getNodeIntersection(Node head1, Node head2)
{
     Node temp1 = head1;
     Node temp2 = head2;
     /*Get lengths of both the lists*/
     int len1 = this.getLength(temp1);
     int len2 = this.getLength(temp2);

     int diff = getAbs(len1,len2); //get absolute difference of the two lengths

     //Iterate through the bigger list first so both list have equal nodes left
     if(len1 > len2)
     {
        int count = 0;
        while(count < diff)
        {
            temp1 = temp1.getNext();
            count++;
        }
     }
     else
     {
             int count = 0;
            while(count < diff)
        {
            temp2 = temp2.getNext();
            count++;
        }
     }

     Node nIntersect = null;
     while(temp1 != temp2)
     {
        temp1 = temp1.getNext();
        temp2 = temp2.getNext();

        if(temp1 == temp2)
        {
            nIntersect = temp1;
        }

     }

     return nIntersect;

}

I am having trouble calculating the time complexity for this. 我在计算时间复杂度时遇到了麻烦。 My understanding is that I first find lengths of both the list which would be N + N. Then I iterate through the bigger list first which is again N and then i iterate through both the lists till they intersect which is again N nodes. 我的理解是,我首先找到两个列表的长度,即N +N。然后,我首先遍历较大的列表,又是N,然后遍历这两个列表,直到它们相交,即又是N个节点。 I was thinking that that time complexity for this algorithm would be O(N). 我当时认为该算法的时间复杂度为O(N)。 To my surprise after solving this algorithm i found similar solutions on some blogs and the time complexity for this is O(M+N). 使我惊讶的是,在解决了该算法之后,我在一些博客上发现了类似的解决方案,其时间复杂度为O(M + N)。 I don't understand why? 我不明白为什么? I thought that as N goes to infinite The larger value would dominate so it would be O(max(m,n)) which would either be O(n) or O(m) depending on which one is larger. 我认为当N趋于无限大时,较大的值将占主导地位,因此它将是O(max(m,n)),取决于哪个较大,它可能是O(n)或O(m)。 Can someone please clarify this for me? 有人可以帮我澄清一下吗?

O(max(n, m)) is O(n + m) because max(n, m) <= n + m . O(max(n, m))O(n + m)因为max(n, m) <= n + m It is a precise bound because max(n, m) >= (n + m) / 2 . 这是一个精确的界限,因为max(n, m) >= (n + m) / 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM