【问题标题】:Calculating time complexity of a Iterative algorithm计算迭代算法的时间复杂度
【发布时间】:2015-03-09 15:06:38
【问题描述】:

我正在处理两个单链表在某个时间点合并的问题。下图说明了这个概念。

我想找到并返回它们相交的节点。我只提到了两个列表的负责人。以下是我想出的算法。

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;

}

我无法为此计算时间复杂度。我的理解是,我首先找到两个列表的长度,即 N + N。然后我首先遍历更大的列表,再次是 N,然后我遍历两个列表,直到它们相交,这又是 N 个节点。我在想这个算法的时间复杂度是 O(N)。令我惊讶的是,在解决了这个算法后,我在一些博客上找到了类似的解决方案,时间复杂度为 O(M+N)。我不明白为什么?我认为随着 N 趋于无限,较大的值将占主导地位,因此它将是 O(max(m,n)) ,这将是 O(n) 或 O(m) ,具体取决于哪个更大。有人可以帮我澄清一下吗?

【问题讨论】:

  • 我认为你说的是​​真的。 max(m,n) 是表达同一事物的一种不同方式,但是当有两个因素时,例如顶点和边,通常的做法是不做任何假设并像这样写。不过不要相信我的话,它只是让我想到了很多 O(v+e) 的图算法。

标签: java algorithm linked-list


【解决方案1】:

O(max(n, m))O(n + m),因为 max(n, m) &lt;= n + m。这是一个精确的界限,因为max(n, m) &gt;= (n + m) / 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 2019-01-26
    • 2011-06-21
    • 1970-01-01
    • 2023-03-24
    • 2021-08-25
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多