简繁EN

LeetCodeNo. 109

【LeetCode with Python】 148. Sort List

目录

题目

原题页面:https://leetcode.com/problems/sort-list/
题目类型:Linked List, Sort
难度评价:Medium
类似题目:(E) Merge Two Sorted Lists, (M) Sort Colors, (M) Insertion Sort List

Sort a linked list in O(n log n) time using constant space complexity.


分析

链表的归并排序。findMiddle用快慢指针找中点:slow从head出发,fast从head.next出发,fast每次走两步,slow每次走一步;fast走到头时slow停在前半段的最后一个节点,偶数个节点时两半一样长,奇数个节点时前半段多一个。

mergeList在中点断开(mid.next = None),两半分别递归调用mergeList排好,再像合并两个有序链表那样合成一条:用一个哑节点new_head当头,每次取两边较小的节点接上,最后把剩下的一段整个接到末尾,返回new_head.next。

时间复杂度是O(n log n):一共log n层,每层找中点和合并加起来是O(n)。空间上,数组的归并排序合并时要一个O(n)的辅助数组,链表合并只改next指针,不需要辅助数组;不过这是自顶向下的递归,递归栈的深度是log n级别,所以额外空间是O(log n),严格说达不到题目要求的常数空间。

要严格做到常数空间,得改成自底向上的迭代归并:先把相邻的长度为1的段两两合并,再按长度2、4、8……合并,不用递归,我的代码没有这样写。


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution:

def findMiddle(self, head):
slow = head
fast = head.next
while None != fast and None != fast.next:
fast = fast.next.next
slow = slow.next
return slow

def mergeList(self, head):
if None == head.next:
return head
mid = self.findMiddle(head)
right_head = mid.next
mid.next = None
left_list = self.mergeList(head)
right_list = self.mergeList(right_head)
new_head = ListNode(-1)
new_tail = new_head
left_node = left_list
right_node = right_list
while None != left_node and None != right_node:
if left_node.val <= right_node.val:
new_tail.next = left_node
left_node = left_node.next
else:
new_tail.next = right_node
right_node = right_node.next
new_tail = new_tail.next
new_tail.next = left_node if None != left_node else right_node
return new_head.next

# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if None == head: # leetcode will input this !
return None
return self.mergeList(head)

本文地址:https://xnerv.wang/leetcode-sort-list/