Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
Hide Tags
Linked List
两个单项链表,判断是否存在交集,如上图很清晰,最直观的方法是
for list1 begin to last
for list2 begin to last
if list2==list1 success
end
end
时间是O(nm),空间挺少的O(1)。如何提高呢?
- 遍历list1 ,将其节点存在hash_table
- 遍历list2,如果已经在hash_table中,那么存在
利用hash_table 可以提升时间到O(n+m),可是空间变O(n)了
1 class Solution { 2 public: 3 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 unordered_map<ListNode*,int> m; 5 while(headA!=NULL){ 6 m[headA] = 1; 7 headA=headA->next; 8 } 9 while(headB!=NULL){ 10 if(m[headB]==1) return headB; 11 headB=headB->next; 12 } 13 return NULL; 14 } 15 };