Merge k Sorted Lists - LeetCode 23 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 พ.ย. 2024

ความคิดเห็น • 4

  • @deepakjyoti8355
    @deepakjyoti8355 หลายเดือนก่อน +1

    Your videos are informative, entertaining and educational.

  • @Drdoggo24
    @Drdoggo24 หลายเดือนก่อน

    Great consistency, motivated me to start again 😅 high time I do lol
    Also I love the way you’re using collections and heaps. Although I gain an overall intuition before I watch the explanation, it’s hard to code those small things that don’t need coding from scratch. So thanks for keeping it simple !

  • @vinuu.k
    @vinuu.k หลายเดือนก่อน

    Why do you use python3 rather than python...?!

  • @jst8922
    @jst8922 หลายเดือนก่อน

    LC linked list hard question, not actually my favorite topic :P
    I see you used heaps (min), not beginner friendly stuff and complicated solution.
    imho: NC solution is easier to understand:
    # Definition for singly-linked list.
    # class ListNode:
    # def __init__(self, val=0, next=None):
    # self.val = val
    # self.next = next
    class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
    if not lists or len(lists) == 0:
    return None
    while len(lists) > 1:
    mergedLists = []
    for i in range(0, len(lists), 2):
    l1 = lists[i]
    l2 = lists[i + 1] if (i + 1) < len(lists) else None
    mergedLists.append(self.mergeList(l1, l2))
    lists = mergedLists
    return lists[0]
    def mergeList(self, l1, l2):
    dummy = ListNode()
    tail = dummy
    while l1 and l2:
    if l1.val < l2.val:
    tail.next = l1
    l1 = l1.next
    else:
    tail.next = l2
    l2 = l2.next
    tail = tail.next
    if l1:
    tail.next = l1
    if l2:
    tail.next = l2
    return dummy.next