iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 43

[Day 43] Sort List (Medium)

  • 分享至 

  • xImage
  •  

148. Sort List

Solution 1: Merge Sort

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeSortedList(self, head1, head2):
        dummyNode = ListNode()
        ptrCurrHead = dummyNode
        while head1 and head2:
            if head1.val <= head2.val:
                ptrCurrHead.next = head1
                head1 = head1.next
            else: # head1.val > head2.val:
                ptrCurrHead.next = head2
                head2 = head2.next
            ptrCurrHead = ptrCurrHead.next
        
        # list2 is null
        while head1:
            ptrCurrHead.next = head1
            ptrCurrHead = ptrCurrHead.next
            head1 = head1.next
        # list1 is null
        while head2:
            ptrCurrHead.next = head2
            ptrCurrHead = ptrCurrHead.next
            head2 = head2.next

        return dummyNode.next
        

    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        
        ptrFast = ptrSlow = ptrEndOfFirstHalfList = head
        while(ptrFast and ptrFast.next):
            ptrEndOfFirstHalfList = ptrSlow
            ptrSlow = ptrSlow.next            
            ptrFast = ptrFast.next.next
        
        ptrEndOfFirstHalfList.next = None
        headOfLftHalf = self.sortList(head)
        headOfRhtHalf = self.sortList(ptrSlow)
        head = self.mergeSortedList(headOfLftHalf, headOfRhtHalf)

        return head

Time Complexity: O(NLog(N))
Space Complexity: O(Log(N)) // The recursive call need stack

Solution 2: Quick Sort

Time Complexity: O(NLog(N))
Space Complexity: O(Log(N))

Reference


上一篇
[Day 42] Unique Binary Search Trees (Medium)
下一篇
[Day 44] Lowest Common Ancestor of a Binary Tree (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言