在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
看到题目就知道要二分,这里用的是递归版归并:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
pre_slow, slow, fast = head, head, head # 快慢指针找中点分成两个链表
while fast and fast.next:
pre_slow = slow
slow = slow.next
fast = fast.next.next
pre_slow.next = None
l1, l2 = self.sortList(head), self.sortList(slow)
return self.merge(l1, l2)
def merge(self, l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1.next = self.merge(l1.next, l2)
return l1
else:
l2.next = self.merge(l1, l2.next)
return l2