Sort a linked list in O(n log n) time using constant space complexity.
链表排序~可以用merge sort~找到链表的中点,然后对左右进行递归,最后再把两段lists合并~Merge Sort的时间复杂度为O(nlogn)~
class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if head is None or head.next is None: return head
slow, fast = head, head
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
head1, head2 = head, slow.next
slow.next = None
head1 = self.sortList(head1)
head2 = self.sortList(head2)
return self.mergeSort(head1, head2)
def mergeSort(self, head1, head2):
newHead = ListNode(0)
cur = newHead
while head1 and head2:
if head1.val < head2.val:
cur.next = head1
head1 = head1.next
else:
cur.next = head2
head2 = head2.next
cur = cur.next
if head1:
cur.next = head1
if head2:
cur.next = head2
return newHead.next
本文介绍了一种使用归并排序在O(n log n)时间内完成链表排序的方法,并提供了详细的Python实现代码。通过寻找链表中点,递归地对左右两部分进行排序,最后将这两部分合并。
136

被折叠的 条评论
为什么被折叠?



