leetcode 148.排序链表(python)
坚持每天刷, 今天感觉刷出感觉了, 果然量变引起质变.
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
递归 + 归并
class Solution(object):
def sortList(self, head):
# 递归 + 归并
if not head or not head.next:
return head
fast, slow = head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
start = slow.next
slow.next = None
l, r = self.sortList(head), self.sortList(start)
return self.merge(l, r)
def merge(self, l, r):
if not l or not r:
return l or r
tmp = p = ListNode(0)
while l and r:
if l.val < r.val:
p.next = l
l = l.next
else:
p.next = r
r = r.next
p = p.next
p.next = l or r
return tmp.next