• 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;
        }
    }
  • 相关阅读:
    第一次冲刺团队绩效评估
    各组意见汇总及我组改进方案
    对其他小组的评价和建议
    检查第一组博客状况
    第一次冲刺-站立会议10
    第一次冲刺-站立会议09
    第一次冲刺-站立会议08
    敏捷软件需求:团队、项目群与企业级的精益需求实践 阅读笔记二
    敏捷软件需求:团队、项目群与企业级的精益需求实践 阅读笔记一
    问题账户需求分析
  • 原文地址:https://www.cnblogs.com/zhangyuhao/p/11452441.html
Copyright © 2020-2023  润新知