Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 21 · Merge

Merge Two Sorted Lists

LeetCode 21 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Dummy head + pick the smaller node.

எளிதுLinked ListRecursion
LeetCode இல் திற ↗

நான் Merge Two Sorted Lists (LeetCode 21) ஐ இப்படித் தீர்த்தேன் — Merge பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Use a dummy head and keep attaching the smaller of the two current nodes. When one list runs out, attach the remainder of the other in one step.

Approach

  1. 1

    temp starts at a dummy node.

  2. 2

    Attach the smaller head and advance that list.

  3. 3

    Attach whatever is left over.

நான் எப்படித் தீர்த்தேன்

Iterative mergePythonO(m+n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(-1)
        temp = dummy
        while list1 and list2:
            if list1.val<=list2.val:
                temp.next = list1
                temp = temp.next
                list1=list1.next
            else:
                temp.next = list2
                temp = temp.next
                list2=list2.next
        if list2:
            temp.next = list2
        if list1:
            temp.next = list1
        return dummy.next
        
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Merge Two Sorted Lists — அடிக்கடி கேட்கப்படும் கேள்விகள்

Merge Two Sorted Lists பின்னாலுள்ள intuition என்ன?

Use a dummy head and keep attaching the smaller of the two current nodes. When one list runs out, attach the remainder of the other in one step.

Merge Two Sorted Lists (LeetCode 21) ஐ எப்படித் தீர்ப்பது?

1. temp starts at a dummy node. 2. Attach the smaller head and advance that list. 3. Attach whatever is left over.

Merge Two Sorted Lists இன் time மற்றும் space complexity என்ன?

Time: O(m + n). Space: O(1). (Accepted approach: Iterative merge.)

Merge Two Sorted Lists இல் பொதுவான தவறுகள் என்ன?

Use ≤ to keep the merge stable.