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.