148. Sort List
https://leetcode.com/problems/sort-list/
solution
归并排序
# https://www.geeksforgeeks.org/merge-sort-for-linked-list/?ref=lbp
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
# Split the list into two halves
left = head
right = self.getMid(head)
tmp = right.next
right.next = None
right = tmp
left = self.sortList(left)
right = self.sortList(right)
return self.merge(left, right)
def getMid(self, head):
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
# Merge the list
def merge(self, list1, list2):
newHead = tail = ListNode()
while list1 and list2:
if list1.val > list2.val:
tail.next = list2
list2 = list2.next
else:
tail.next = list1
list1 = list1.next
tail = tail.next
if list1:
tail.next = list1
if list2:
tail.next = list2
return newHead.next时间复杂度:O() 空间复杂度:O()
快排
时间复杂度:O() 空间复杂度:O()
follow up
Last updated