Leetcode-148. Sort List-python
问题描述:
Sort a linked list in O(n log n) time using constant space complexity.
将一个链表排序,限制了时间复杂度和空间复杂度
Example:
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
算法(归并排序):
由于限制了时间复杂度为O(nlogn),所以我们归并排序进行求解,将链表分成两部分,每一部分单独进行排序,然后合并起来,将链表平分的方式我们用到快慢指针的方式,快指针走到末尾时,慢指针才到中间。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
slow,faster,pre = head,head,head
while faster and faster.next:
pre = slow
slow = slow.next
faster = faster.next.next
pre.next = None
return self.merge(self.sortList(head),self.sortList(slow))
def merge(self,l1,l2):
if l1 is None:
return l2
if l2 is None:
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
不过似乎递归并不是静态空间。。。