Merge Two Sorted Lists
LeetCode 21 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Dummy head + pick the smaller node.
ನಾನು 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
temp starts at a dummy node.
- 2
Attach the smaller head and advance that list.
- 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.