148. Sort List (题目链接)
Medium
Sort a linked list in O(n log n) time using constant space complexity.
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(n log n),常用排序算法时间复杂度为O(n log n)快排,归并,堆排序
常见排序算法总结:常见排序算法总结
这个题目可以使用归并排序去实现,这个题目结合[Leetcode] 21. Merge Two Sorted Lists 和归并排序
这个题目还用到了快慢指针,使用快慢指针可以快速求链表的中间节点,快慢指针还常用于链表跟环相关的题目。
class Solution:
def merge(self, node1, node2):
if not node1 or not node2:
return node1 or node2
if node1.val <= node2.val:
node1.next = self.merge(node1.next, node2)
return node1
else:
node2.next = self.merge(node2.next, node1)
return node2
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
slow, fast = head, head
pre_slow = slow
while fast:
pre_slow = slow
slow = slow.next
fast = fast.next.next if fast.next else None
pre_slow.next = None
return self.merge(self.sortList(head), self.sortList(slow))