一天两道力扣(1)

解法1:

python 复制代码
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        A, B = headA, headB
        while(A != B):
            A = A.next if A else headB
            B = B.next if B else headA 
        return A
        

解析:简单来说就是两个人同时走路,相遇的点就是交叉点,因为相遇了就说明路程一样,两次循环找到交叉点。

解法2:

python 复制代码
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        s = set()
        p, q = headA, headB
        while p:
            s.add(p)
            p = p.next
        while q:
            if q in s:
                return q
            q = q.next
        return None

解析:先将链表A放在哈希表里面,然后遍历B将其逐个与哈希表对比。

解法3:

python 复制代码
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        s1, s2 = [], []
        p, q = headA, headB
        while p:
            s1.append(p)
            p = p.next
        while q:
            s2.append(q)
            q = q.next
        ans = None
        i, j = len(s1) - 1, len(s2) - 1
        while i >= 0 and j >= 0 and s1[i] == s2[j]:
            ans = s1[i]
            i, j = i - 1, j - 1
        return ans
        

解析:用栈先进后出的思想,倒着对比,直到找到不一样的地方。

解法4:

python 复制代码
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        s1, s2 = 0, 0
        p, q = headA, headB
        while p:
            p = p.next
            s1 += 1
        while q:
            q = q.next
            s2 += 1
        p, q = headA, headB
        for i in range(s1 - s2):
            p = p.next
        for i in range(s2 - s1):
            q = q.next
        while p and q and p != q:
            p = p.next
            q = q.next
        return p
        

解析:谁长谁先遍历。先遍历到相同长度,然后直接对比就好了。

python 复制代码
class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        if not root or root == p or root == q: return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if not left and not right: return
        if not right: return left
        if not left: return right
        return root
        
相关推荐
666HZ6669 小时前
数据结构2.0 线性表
c语言·数据结构·算法
西伯利亚狼_J202010 小时前
260109introduceEN
职场和发展
实心儿儿10 小时前
Linux —— 基础开发工具5
linux·运维·算法
charlie11451419111 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
清木铎12 小时前
leetcode_day4_筑基期_《绝境求生》
算法
清木铎12 小时前
leetcode_day10_筑基期_《绝境求生》
算法
j_jiajia12 小时前
(一)人工智能算法之监督学习——KNN
人工智能·学习·算法
源代码•宸13 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
我命由我1234513 小时前
Photoshop - Photoshop 工具栏(57)模糊工具
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
Jasmine_llq14 小时前
《CF280C Game on Tree》
数据结构·算法·邻接表·深度优先搜索(dfs)·树的遍历 + 线性累加统计