-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntersectionOfTwoLinkedLists.java
60 lines (52 loc) · 1.46 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
package linkedlist;
import linkedlist.LinkedListTest.ListNode;
/**
* @author Shogo Akiyama
* Solved on 12/03/2019
*
* 160. Intersection of Two Linked Lists
* https://leetcode.com/problems/intersection-of-two-linked-lists/
* Difficulty: Easy
*
* Approach: Recursion with Count
* Runtime: 1 ms, faster than 99.11% of Java online submissions for Intersection of Two Linked Lists.
* Memory Usage: 38.5 MB, less than 51.43% of Java online submissions for Intersection of Two Linked Lists.
*
* Time Complexity: O(m + n)
* Space Complexity: O(m + n) for recursive stack, O(1) without counting recursive stack
* Where m and n are the numbers of nodes in the linked lists respectively
*
* @see LinkedListTest#testIntersectionOfTwoLinkedLists()
*/
public class IntersectionOfTwoLinkedLists {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int countA = count(headA);
int countB = count(headB);
return recurse(headA, headB, countA - countB);
}
private int count(ListNode n) {
if (n == null) {
return 0;
} else {
return count(n.next) + 1;
}
}
private ListNode recurse(ListNode a, ListNode b, int diff) {
if (a == null || b == null) {
return null;
}
if (a == b) {
return a;
}
if (diff > 0) {
return recurse(a.next, b, diff - 1);
} else if (diff < 0) {
return recurse(a, b.next, diff + 1);
} else {
return recurse(a.next, b.next, diff);
}
}
}