148. 排序链表
-
解题思路:在链表上使用排序算法。注意,不能使用快排,因为快排的最差时间复杂度是
O(n^2)
,数组形式的快排,以随机数划分能够得到O(n*logn)
,但是链表的形式,不太好以随机数的方式划分。所以最好的排序方法是使用归并排序。- 先用快慢指针,将链表分成两部分,然后两部分分别归并排序,得到两个链表的头和尾。然后再
merge
即可
- 先用快慢指针,将链表分成两部分,然后两部分分别归并排序,得到两个链表的头和尾。然后再
-
代码
class Solution: def process(self, node: Optional[ListNode]) -> (Optional[ListNode], Optional[ListNode]): slow = node if slow.next == None: return slow, slow fast = slow.next while fast and fast.next: slow = slow.next fast = fast.next if fast == None: break fast = fast.next # 分别有序 tmp = slow.next slow.next = None head1, tail1 = self.process(node) head2, tail2 = self.process(tmp) # 合并 ans_head = None ans_tail = tail1 if tail1.val >= tail2.val else tail2 if head1.val <= head2.val: ans_head = head1 head1 = head1.next else: ans_head = head2 head2 = head2.next cur = ans_head 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 ans_head, ans_tail def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head == None: return None head1, _ = self.process(head) return head1
标签:
leetcode刷题
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理