[英]How to determine the space and time complexity of these two double linked list algorithms?
[英]How to determine the space and time complexity of these two algorithms?
我今天在HackerRank上进行一种算法练习: https ://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists
我决定用两种解决方案来解决这个问题。
第一种算法,基于弗洛伊德算法:
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
}
*/
int FindMergeNode(Node headA, Node headB) {
// Complete this function
// Do not write the main method.
int length1 = countLength(headA);
int length2 = countLength(headB);
int d = Math.abs(length1 - length2);
return (length1 > length2) ?
findIntersection(d, headA, headB) : findIntersection(d, headB, headA);
}
int countLength(Node head) {
Node current = head;
int counter = 0;
while (current != null) {
current = current.next;
counter++;
}
return counter;
}
int findIntersection(int d, Node headA, Node headB) {
Node currentA = headA;
Node currentB = headB;
for (int i = 0; i < d; i++) {
currentA = currentA.next;
}
while (currentA != null && currentB != null) {
if (currentA == currentB) return currentA.data;
currentA = currentA.next;
currentB = currentB.next;
}
return -1;
}
第二种算法,使用一个外部和内部循环:
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
}
*/
int FindMergeNode(Node headA, Node headB) {
Node currentA = headA;
while (currentA != null) {
Node currentB = headB;
while (currentB != null) {
if (currentA == currentB) {
return currentA.data;
}
currentB = currentB.next;
}
currentA = currentA.next;
}
return -1;
}
老实说,我确信第一种算法的性能优于第二种算法。 我想使用SPACE和TIME COMPLEXITY演示这种性能,但我没有主导这些主题。
根据材料,此解决方案应为时间复杂度:O(N)。 但是我不太确定第一个算法是O(N)。
第一种算法扫描headA
和headB
一次以找到长度,然后跳过较长链的多余元素,然后并行扫描两个链。 时间复杂度与链的长度成正比,因此为O(N)。 扫描列表2、3或5次无关紧要,只要该数目恒定,时间复杂度仍为O(N)。
第二种算法更糟糕,对于合并点之前headA
每个元素,它都会扫描整个headB
。 在最坏的情况下,当列表不会在最后一个节点相交时,它会扫描的所有元素headB
的每个元素headA
。 因此,其时间复杂度为O(N ^ 2)。
两种算法的空间复杂度均为O(1),因为在这两种算法中都使用了常量存储(一堆局部变量),无论输入列表的大小如何,它们都不会改变。
第一个是O(N),其中N抽象是两个列表长度中最大的一个。 由于您有两个for循环,每个循环的成本最多为N,因此在最坏的情况下,第一个算法将花费2 N个周期才能结束。 因此,由于O隐藏常数因子,算法为O(N)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.