[英]Calculating time complexity of a Iterative algorithm
我正在处理两个单链列表在某个时刻合并的问题。 下图说明了此概念。
我想找到并返回它们都相交的节点。 我只提到两个列表的头。 以下是我想出的算法。
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)。 有人可以帮我澄清一下吗?
O(max(n, m))
为O(n + m)
因为max(n, m) <= n + m
。 这是一个精确的界限,因为max(n, m) >= (n + m) / 2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.