leetcode(160):Intersection of Two Linked Lists

news/2024/7/3 21:26:12 标签: leetcode

题目:Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:

A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3
begin to intersect at node c1.
【note】
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
题目分析:
第一版:一拿到题目,我对题目的分析,以例子来进行分析,断开a1与a2的连接关系,然后使a1指向b1,从b1如果能遍历到a2,则说明a2在相交的链上,也就是在相同的子链上。依次处理每个A链上的结点,最终得到需要的结果。
对处理的结果是超时,,这个算法的时间复杂度都是O(n^2)了吧。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA == None or headB == None:
            return None
        node1 = headA
        node2 = node1.next
        while node2:
            node1.next = headB
            if self.isnext(headB, node2):
                node1.next = node2
                return node2
            else:
                node1.next = node2
                node1 = node2
                node2 = node1.next
        return None

    def isnext(self, headB, next_n):
        node = headB
        while node:
            if node == next_n:
                return True
        return False

第二种思路:成立的条件在于二个链表之前有不同的地方,也就是a1,b1应该是不为0的,在这种条件下,我们将B链表的最后节点指向A节点,这样可以利用龟兔赛跑算法来求解,也就是Floyd判圈算法,还可以得到圈的起点,也就是相交点。对于二个链表从头结点开始可能就与另一个链表相同的情形下,是不能利用判圈算法来进行判断的,这个时候需要特殊的进行判断。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA == None or headB == None:
            return None
        node = headB
        nodea = headA
        while node:
            if node == headA:
                return headA
            if node.next == None:
                while nodea:
                    if nodea == headB:
                        return headB
                    else:
                        nodea = nodea.next
                node.next = headA
                break
            else:
                node = node.next          
        node = self.iscycle(headB)
        nodeB = headB
        while nodeB.next:
            if nodeB.next == headA:
                nodeB.next = None
            else:
                nodeB = nodeB.next
        return node



    def iscycle(self, head):
        if head.next == None or head.next.next == None:
            return None
        fast = head.next.next
        slow = head.next
        while fast:
            if slow == fast:
                slow = head
                while True:
                    if slow == fast:
                        return slow
                    else:
                        slow = slow.next
                        fast = fast.next
            else:
                try:
                    fast = fast.next.next
                    slow = slow.next
                except:
                    return None
        return None

好的,终于把这个问题解决了,看一下大佬们的思路,好像是很简单的说。。

class Solution:
    # @param two ListNodes
    # @return the intersected ListNode
    def getIntersectionNode(self, headA, headB):
        if headA is None or headB is None:
            return None

        pa = headA # 2 pointers
        pb = headB

        while pa is not pb:
            # if either pointer hits the end, switch head and continue the second traversal, 
            # if not hit the end, just move on to next
            pa = headB if pa is None else pa.next
            pb = headA if pb is None else pb.next

        return pa # only 2 ways to get out of the loop, they meet or the both hit the end=None

http://www.niftyadmin.cn/n/1798854.html

相关文章

ecshop做淘宝客

第一步下载文件。 安装好ECSHOP,然后通过PTF工具下载2个文件到本地进行修改。这个2个文件分别是goods.dwt和goods_list.lbi文件,位置在你根目录下的 \themes\你模板名称\goods.dwt,根目录下的\themes\你模板名称\library\goods_list.lbi&…

华东理工某ACMer总结

做算法和作技术哪个难? 都很难, 没有可比性. 但是算法做得好的可以转行做技术, 技术做得好的想转行做算法却很困难.我是08年下半年将近期末的时候加入华理ACM队的. 我高中的时候没有编程经验, 数学也不好, 高考数学刚及格. 因为第二工业大学的网络工程专业的分数是最低的, 所以…

读书笔记-----数据库(一)数据库的简要介绍

在这一部分我们讲述关系型数据库的基本问题。在这一部分中,我们讲述什么是数据库,数据库使用的背景,数据库中的基本概念,数据库的历史,以及对于关系型数据库的一些基本的介绍。 对于数据库而言,是存放数据…

centos git版本服务器配置

centos git版本服务器配置 在服务器上安装git及做些操作 - 执行命令sudo yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-devel- 同时下载git-1.8.2.3.tar.gz文件,wget https://www.kernel.org/pub/software/scm/git/git-1.8.2…

leetcode(100):Same Tree

题目:Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 题目分析:判断二棵树是否相同&#xff0…

裁剪图片中遇到问题,怎么解决?

2019独角兽企业重金招聘Python工程师标准>>> 问题代码: Intent cropIntent new Intent("com.android.camera.action.CROP");cropIntent.setType("image/*");cropIntent.putExtra("crop", "true");cropIntent.p…

POJ 1847 最短路问题 dijkstra算法的实现

首先自己练习了一下实现dijkstra算法,可以把dj算法与prim算法对比记忆,要理解pre数组、min数组、V标记数组的含义! //单源最短路径,dijkstra算法,邻接阵形式,复杂度O(n^2)//求出源s到所有点的最短路经,传入图的顶点数n,(有向)邻接矩阵mat//返回到各点最…

leetcode(101):Symmetric Tree

题目:Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 对于题目的分析:这个题目要求判断给定的这棵树是不是关于根节点对称。对于根节点而言,首先需要判断根节点是不是为None形式&#…