- 题目描述
输入:[1,2,3,5,7,8,9]与[0,10,5,7,8,9]
输出:[5]
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> visited = new HashSet<ListNode>();
ListNode temp = headA;
while(temp != null){
visited.add(temp);
temp = temp.next;
}
temp = headB;
while(temp != null){
if(visited.contains(temp)){
return temp;
}
temp = temp.next;
}
return null;
}
首先想到的是用哈希表,但是时间复杂率略高,还有待优化。