题目描述:
Sort a linked list in O(n log n) time using constant space complexity.
解题思路:
排序不难,难的是在题目给定的条件下进行排序。
首先想到快排序。无奈发现单链表中交换元素很麻烦,放弃这个思路。接着想到归并排序,单链表中划分两个区域,归并,都很方便。
自顶向下的归并排序,空间复杂度为log(n)(n为链表长度)。于是想到自底向上归并排序,由于是用循环写的,空间复杂度为O(C),满足题目要求。
解题代码:
class Solution(object):
def sortList(self, head):
if not head or not head.next:
return head
cur, length = head, 0
while cur:
length +=1
cur = cur.next
dummy = ListNode(0)
dummy.next = head
step = 1
while step < length:
tail, cur = dummy, dummy.next
while cur:
left, cur = self.split(cur, step)
right, cur = self.split(cur, step)
tail = self.merge(left, right, tail)
step *= 2
return dummy.next
def split(self, cur, step):
node = cur
while cur and step > 1:
cur = cur.next
step -= 1
if cur:
tmp = cur.next
cur.next = None
cur = tmp
return node, cur
def merge(self, left, right, tail):
while left and right:
if left.val < right.val:
tail.next = left
tail, left = tail.next, left.next
else:
tail.next = right
tail, right = tail.next, right.next
if left:
tail.next = left
if right:
tail.next = right
while tail.next:
tail = tail.next
return tail
小结:
除了快排序,归并排序也很实用。