Leetcode 160. Intersection of Two Linked Lists

在这里插入图片描述
思路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非常重要!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值