思路1: brute force。非常简单nested loop,遍历两个链表,找到第一个相同的node。时间复杂度n^2,空间复杂度1。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p = headA, q = headB;
while(p != null){
q = headB;
while(q != null){
if(p == q){
return q;
}
q = q.next;
}
p = p.next;
}
return null;
}
}
思路2: 方法1的升级版,加一个hashset,将链表1 的node全部放进set中,然后遍历链表2,对于链表2种的每一个node,check是否再set中出现,如果出现,即返回该node。时间复杂度m+n,空间m(m为短的链表的长度)。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set mySet = new HashSet();
ListNode p = headA, q = headB;
while(p != null){
mySet.add(p);
p = p.next;
}
while(q != null){
if(mySet.contains(q)){
return q;
}
q = q.next;
}
return null;
}
}
方法3: 这个方法可以看作two pointer。我是看的discussion区的第一高赞回答。该方法核心思想是要让两个pointer同时到达intersection node。详细解释请看链接:链接。时间复杂度m+n,空间复杂度1。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//if(headA == null || headB == null) return null;
ListNode p = headA, q = headB;
while(p != q){
p = (p == null) ? headB : p.next;
q = (q == null) ? headA : q.next;
}
return p;
}
}
总结:
- 链表题目也可以巧妙运用two poiner,我觉得大概率归功于next方法。
- easy题也要吸收到位,一步步的optimization非常重要!