-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathIntersectionOfTwoLinkedLists.java
85 lines (83 loc) · 2.14 KB
/
IntersectionOfTwoLinkedLists.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package io.ziheng.list.leetcode;
import java.util.Set;
import java.util.HashSet;
/**
* LeetCode 160. Intersection of Two Linked Lists
* https://leetcode.com/problems/intersection-of-two-linked-lists/
*/
public class IntersectionOfTwoLinkedLists {
/**
* Intersection of Two Linked Lists
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* @param headA
* @param headB
* @return ListNode
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
Set<ListNode> aSet = new HashSet<>();
ListNode currentNode = headA;
while (currentNode != null) {
aSet.add(currentNode);
currentNode = currentNode.next;
}
currentNode = headB;
while (currentNode != null) {
if (aSet.contains(currentNode)) {
return currentNode;
}
currentNode = currentNode.next;
}
return null;
}
/**
* more elegant way
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* @param headA
* @param headB
* @return ListNode
*/
public ListNode getIntersectionNode0(ListNode headA, ListNode headB) {
int lenA = findListLength(headA);
int lenB = findListLength(headB);
ListNode pA = headA;
ListNode pB = headB;
if (lenA > lenB) {
int diff = lenA - lenB;
for (int i = 0; i < diff; i++) {
pA = pA.next;
}
} else {
int diff = lenB - lenA;
for (int i = 0; i < diff; i++) {
pB = pB.next;
}
}
while (pA != null) {
if (pA == pB) {
return pA;
}
pA = pA.next;
pB = pB.next;
}
return null;
}
private int findListLength(ListNode head) {
int cnt = 0;
ListNode currentNode = head;
while (currentNode != null) {
cnt++;
currentNode = currentNode.next;
}
return cnt;
}
}
/* EOF */