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;
        }
    }
  • 相关阅读:
    曾经拥有,今生无悔
    WinRAR 4.20 beta2 key!注册文件 注册码
    加谁的QQ,并聊天‘
    自己读c
    字符串和字符数组做函数参数是的区别,
    数组
    *p和++对p的影响和对*p的影响
    字符串赋给指针
    memset函数,还没看2013.12.19
    strtock函数小结。
  • 原文地址:https://www.cnblogs.com/zhangyuhao/p/11452441.html
Copyright © 2011-2022 走看看