JZ52 两个链表的第一个公共结点
题源 👉 两个链表的第一个公共结点_牛客题霸_牛客网 (nowcoder.com)
题目描述:
具体实现:
方法一:暴力枚举
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
for(ListNode a = pHead1; a != null; a = a.next )
for(ListNode b = pHead2; b != null; b = b.next )
if(a == b) return a;
return null;
}
时间:O(n×m)
空间:O(1)
方法二:栈解法 👉 【宫水三叶の剑指精选】一题五解 :「朴素解法」&「栈解法」&「Set 解法」&「差值法」&「等值法」_牛客博客 (nowcoder.net)
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
Deque<ListNode> d1 = new ArrayDeque<>();
Deque<ListNode> d2 = new ArrayDeque<>();
while(pHead1 != null){
d1.add(pHead1);
pHead1 = pHead1.next;
}
while(pHead2 != null){
d2.add(pHead2);
pHead2 = pHead2.next;
}
ListNode ans = null;
while(!d1.isEmpty() && !d2.isEmpty() && d1.peekLast()==d2.peekLast() ){
ans = d1.pollLast();
d2.pollLast();
}
return ans;
}
时间:O(n + m)
空间:O(n + m)
方法三:Set 👉 【宫水三叶の剑指精选】一题五解 :「朴素解法」&「栈解法」&「Set 解法」&「差值法」&「等值法」_牛客博客 (nowcoder.net)
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
Set<ListNode> set = new HashSet<>();
while(pHead1 != null){
set.add(pHead1);
pHead1 = pHead1.next;
}
while(pHead2 != null && !set.contains(pHead2)) pHead2 = pHead2.next;
return pHead2;
}
时间:O(n + m)
空间:O(n)
方法四:差值法 👉 【宫水三叶の剑指精选】一题五解 :「朴素解法」&「栈解法」&「Set 解法」&「差值法」&「等值法」_牛客博客 (nowcoder.net)
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int c1 = 0, c2 = 0;
ListNode p1 = pHead1, p2 = pHead2;
while(p1 != null){
c1++;
p1 = p1.next;
}
while(p2 != null){
c2++;
p2 = p2.next;
}
int d = c1 - c2;
if(d > 0){
while(d-- > 0) pHead1 = pHead1.next;
}else if(d < 0){
d = -d;
while(d-- > 0) pHead2 = pHead2.next;
}
while(pHead1 != pHead2){
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
时间:O(n + m)
空间:O(1)