Scribbling

LeetCode: 160. Intersection of Two Linked Lists 본문

Computer Science/Coding Test

LeetCode: 160. Intersection of Two Linked Lists

focalpoint 2021. 12. 2. 20:54

O(1) Memory로 어떻게 풀지 고민해보았다.

방법은 두 List의 node 갯수를 파악하는 것이다.

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

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        m, n = 0, 0
        cur = headA
        while cur != None:
            m += 1
            cur = cur.next
        cur = headB
        while cur != None:
            n += 1
            cur = cur.next
        
        if m >= n:
            for t in range(m-n):
                headA = headA.next
        else:
            for t in range(n-m):
                headB = headB.next
        
        curA, curB = headA, headB
        while curA:
            if curA == curB:
                return curA
            curA = curA.next
            curB = curB.next
        return None

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 179. Largest Number  (0) 2021.12.04
LeetCode: 172. Factorial Trailing Zeroes  (0) 2021.12.04
LeetCode: 162. Find Peak Element  (0) 2021.12.01
LeetCode: 155. Min Stack  (0) 2021.11.30
LeetCode: 152. Maximum Product Subarray  (0) 2021.11.29