FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Intersection of two linked lists · didi0613/leetcode-javascript@33e992f · GitHub

Commit 33e992f

Browse files
committed
Intersection of two linked lists
1 parent a6f1b89 commit 33e992f

1 file changed

Lines changed: 32 additions & 12 deletions

File tree

‎intersection-of-two-linked-lists.js‎

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,41 @@
1212
* @return {ListNode}
1313
*/
1414
var getIntersectionNode = function(headA, headB) {
15-
var hashmap = [];
16-
var ret = null;
17-
while(headA) {
18-
hashmap.push(headA.val);
19-
headA = headA.next;
15+
var lenA = 0, lenB = 0;
16+
var pa = headA;
17+
var pb = headB;
18+
while(pa) {
19+
lenA++;
20+
pa = pa.next;
2021
}
2122

22-
while(headB) {
23-
if(hashmap.includes(headB.val)) {
24-
ret = headB;
25-
break;
26-
} else {
27-
headB = headB.next;
23+
while(pb) {
24+
lenB++;
25+
pb = pb.next;
26+
}
27+
28+
if(lenA >= lenB) {
29+
var diff = lenA - lenB;
30+
pa = headA;
31+
pb = headB;
32+
while(diff) {
33+
pa = pa.next;
34+
diff--;
35+
}
36+
} else {
37+
var diff2 = lenB - lenA;
38+
pa = headA;
39+
pb = headB;
40+
while(diff2) {
41+
pb = pb.next;
42+
diff2--;
2843
}
2944
}
3045

31-
return ret;
46+
while(pa !== pb) {
47+
pa = pa.next;
48+
pb = pb.next;
49+
}
50+
51+
return pa;
3252
};

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL