leecode21,合并有序链表,迭代法+递归法(注意递归法的思考)
## 递归法 class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 elif l2 is None: return l1 elif l1.val<=l2.val: l1.next = self.mergeTwoLists(l1.next,l2) return l1 else: l2.next = self.mergeTwoLists(l1,l2.next) return l2 ## 迭代法 class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: prehead = ListNode(-1) prev = prehead while l1 and l2: if l1.val <= l2.val: prev.next = l1 l1 = l1.next else: prev.next = l2 l2 = l2.next prev = prev.next # 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可 prev.next = l1 if l1 is not None else l2 return prehead.next
leecode88,合并两个有序数组,要求空间复杂度为O(1),逆向双指针
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ p1 = m-1 p2 = n-1 tail = m+n-1 while p1>=0 or p2>=0: if p1 == -1: nums1[tail] = nums2[p2] p2 -= 1 elif p2 == -1: nums1[tail] = nums1[p1] p1 -= 1 elif nums1[p1]>nums2[p2]: nums1[tail] = nums1[p1] p1 -= 1 else: nums1[tail] = nums2[p2] p2 -= 1 tail -= 1
leecode148 排序链表,归并排序
leecode23,合并k个升序链表