题目:
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
思路:
用归并思想,但是链表排序和数组排序有所不同,数组是可以直接拿到中间索引的,而链表得用快慢指针去找。
还有这道题要求的时间复杂度和空间负责度要求也比较高,经常超时了
题解:
这个超时了,还要改进
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not (head and head.next): return head
fast,slow = head.next,head #
while fast and fast.next:
fast,slow = fast.next.next,slow.next #遍历时候 快指针走两步,慢指针走一步
#当快指针走到终点,慢指针就到中点,截断链表
mid,slow.next = slow,None
left = self.sortList(head)
right = self.sortList(mid)
return self.merge2Lists(left,right)
def merge2Lists(self, left: ListNode, right: ListNode) -> ListNode:
if not left:return right
if not right:return left
if left.val < right.val:
left.next = self.merge2Lists(left.next, right)
return left
else:
right.next = self.merge2Lists(left, right.next)
return right
答案题解:
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not (head and head.next): return head
pre, slow, fast = None, head, head
while fast and fast.next: pre, slow, fast = slow, slow.next, fast.next.next
pre.next = None
return self.mergeTwoLists(*map(self.sortList, (head, slow)))
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
if l1.val > l2.val: l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2