zoukankan      html  css  js  c++  java
  • 160--Intersection Of Two Linked List

    public class IntersectionOfTwoLinkedList {
        /*
        解法一:暴力遍历求交点。
                时间复杂度:O(m*n)  空间复杂度:O(1)
         */
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if(headA==null||headB==null)
                return null;
            if (headA==headB)
                return headA;
            ListNode tempA=headA;
            ListNode tempB=headB;
            while (tempA!=null){
                tempB=headB;
                while (tempB!=null){
                    if (tempA==tempB)
                        return tempA;
                    tempB=tempB.next;
                }
                tempA=tempA.next;
            }
            return null;
        }
        /*
        解法二:哈希表求解,思想和解法一差不多,将B存入哈希表,遍历A的节点看是否存在于B
                时间复杂度:O(m+n) 空间复杂度:O(m)或O(n)
         */
        public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
            if(headA==null||headB==null)
                return null;
            if (headA==headB)
                return headA;
            Set<ListNode> set=new HashSet<>();
            ListNode tempB=headB;
            while (tempB!=null){
                set.add(tempB);
                tempB= tempB.next;
            }
            ListNode tempA=headA;
            while (tempA!=null){
                if (set.contains(tempA))
                    return tempA;
                tempA= tempA.next;
            }
            return null;
        }
        /*
        解法三:双指针:当两个链表长度相等时,只需要依次移动双指针,当指针指向的节点相同时,则有交点。
                        但是问题就在于,两个链表的长度不一定相等,所以就要解决它们的长度差。
                        一个字概述这个解法:骚。
         */
        public ListNode getIntersectionNode3(ListNode headA, ListNode headB) {
            if (headA==null||headB==null)
                return null;
            ListNode pA=headA;
            ListNode pB=headB;
            while (pA!=pB){
                pA=pA==null?headB:pA.next;
                pB=pB==null?headA:pB.next;
            }
            return pA;
        }
    }
  • 相关阅读:
    51nod 1117 聪明的木匠:哈夫曼树
    51nod 1010 只包含因子2 3 5的数
    51nod 2636 卡车加油
    51nod 2989 组合数
    51nod 2652 阶乘0的数量 V2
    51nod 1103 N的倍数
    51nod 2489 小b和灯泡
    51nod 1003 阶乘后面0的数量
    51nod 2122 分解质因数
    javascript中的setter和getter
  • 原文地址:https://www.cnblogs.com/zhangyuhao/p/11452441.html
Copyright © 2011-2022 走看看