index
title: 两个链表的第一个公共结点 date: 2019-08-21T11:00:41+08:00 draft: false categories: offer
题目
解决思路
空间复杂度 O(n) 的算法
/**
* 空间 O(n)
*
* @param pHead1
* @param pHead2
* @return
*/
public ListNode FindFirstCommonNode_1(ListNode pHead1, ListNode pHead2) {
Set<ListNode> node1s = new HashSet<>();
while (pHead1 != null) {
node1s.add(pHead1);
pHead1 = pHead1.next;
}
while (pHead2 != null) {
if (node1s.contains(pHead2)) {
return pHead2;
}
pHead2 = pHead2.next;
}
return null;
}空间复杂度 O(1) 的算法
Last updated