problem
Sort a linked list in O(n log n) time using constant space complexity.
solution
因为常见的排序算法时间复杂度描述的都是顺序表,而链表和顺序表的主要区别就是顺序表可以随机存取,而链表的查找效率为 O(n) ,插入、删除操作链表的效率要更高,但是这建立在已知插入位置的情况下。
class Solution(object):
def sortList(self, head):
if not head or not head.next:
return head
#divide the pri list into two lists
pri, slow, fast = head, head, head
while fast and fast.next:
pri = slow
slow = slow.next
fast = fast.next.next
pri.next = None
#sort the two lists
first = self.sortList(head)
second = self.sortList(slow)
#merge and return
return self.merge(first, second)
def merge(self, first, second):
dummy = ListNode(0)
tail = dummy
while first and second:
if first.val < second.val:
tail.next = first
tail = tail.next
first = first.next
else:
tail.next = second
tail = tail.next
second = second.next
if first:
tail.next = first
else:
tail.next = second
return dummy.next
总结
可以把归并排序写成分治的形式,归并排序时间复杂度为 O(nlogn)