我今天正在练习HackerRank的一个算法练习:https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists
我决定用两种解决方案来解决这个问题。
第一种基于Floyd算法的算法:
/*
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)。
答案 0 :(得分:3)
第一个算法扫描headA
和headB
一次以查找长度,然后跳过较长链的额外元素,然后并行扫描两个链。时间复杂度与链的长度成比例,因此它是O(N)。如果您扫描列表2次,3次或5次并不重要,只要该数字是常数,时间复杂度仍为O(N)。
第二种算法更糟糕,对于合并点之前的headA
中的每个元素,它会扫描整个headB
。在最坏的情况下,当列表不在最后一个节点处相交时,它将扫描headB
的每个元素headA
的所有元素。所以这个时间复杂度是O(N ^ 2)。
两种算法的空间复杂度都是O(1),因为无论输入列表的大小如何,都在两个(一堆局部变量)中使用常量存储,不会改变。
答案 1 :(得分:1)
第一个是O(N),其中N是抽象的两个列表长度中最大的一个。由于你有两个for循环,每个都可以花费最大N,在最坏的情况下,第一个算法将花费2 N循环结束。因此,由于O隐藏常数因子,算法为O(N)