题目:
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
解题:
由于链表在归并操作时并不需要像数组的归并操作那样分配一个临时数组空间,所以这样就是常数空间复杂度了,当然这里不考虑递归所产生的。使用快慢指针,寻找中间值。
class Solution(object):
def sortList(self, head):
if not head or not head.next:
return head
slow = fast = head
while fast and fast.next:
pre = slow
slow = slow.next #慢指针走一步
fast = fast.next.next # 快指针走两步
pre.next = None # 将左右两半截断
return self.merge(self.sortList(head), self.sortList(slow))
def merge(self , left,right):
res = cur = ListNode(0)
while left and right:
if left.val < right.val:
cur.next = left
left = left.next
cur = cur.next
else:
cur.next = right
right = right.next
cur = cur.next
if left :
cur.next = left
if right:
cur.next = right
return res.next