一天两道力扣(1)
解法1:
class Solution(object):def getIntersectionNode(self, headA, headB):A, B = headA, headBwhile(A != B):A = A.next if A else headBB = B.next if B else headA return A
解析:简单来说就是两个人同时走路,相遇的点就是交叉点,因为相遇了就说明路程一样,两次循环找到交叉点。
解法2:
class Solution(object):def getIntersectionNode(self, headA, headB):s = set()p, q = headA, headBwhile p:s.add(p)p = p.nextwhile q:if q in s:return qq = q.nextreturn None
解析:先将链表A放在哈希表里面,然后遍历B将其逐个与哈希表对比。
解法3:
class Solution(object):def getIntersectionNode(self, headA, headB):s1, s2 = [], []p, q = headA, headBwhile p:s1.append(p)p = p.nextwhile q:s2.append(q)q = q.nextans = Nonei, j = len(s1) - 1, len(s2) - 1while i >= 0 and j >= 0 and s1[i] == s2[j]:ans = s1[i]i, j = i - 1, j - 1return ans
解析:用栈先进后出的思想,倒着对比,直到找到不一样的地方。
解法4:
class Solution(object):def getIntersectionNode(self, headA, headB):s1, s2 = 0, 0p, q = headA, headBwhile p:p = p.nexts1 += 1while q:q = q.nexts2 += 1p, q = headA, headBfor i in range(s1 - s2):p = p.nextfor i in range(s2 - s1):q = q.nextwhile p and q and p != q:p = p.nextq = q.nextreturn p
解析:谁长谁先遍历。先遍历到相同长度,然后直接对比就好了。
class Solution(object):def lowestCommonAncestor(self, root, p, q):if not root or root == p or root == q: return rootleft = self.lowestCommonAncestor(root.left, p, q)right = self.lowestCommonAncestor(root.right, p, q)if not left and not right: returnif not right: return leftif not left: return rightreturn root