LeetCode - 148. Sort List

本文详细介绍了如何使用归并排序算法对链表进行排序,实现了时间复杂度为O(nlogn)且空间复杂度为O(1)的排序过程。通过迭代方式,将链表分为多个部分并逐一合并,最终得到完全排序的链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

148. Sort Listhttps://leetcode.com/problems/sort-list

排列无序列表
要求:时间复杂度O(nlogn),空间复杂度O(1)

排序算法
1.快排 - 时间复杂度O(nlogn),空间复杂度O(logn) recursion
2.归并排序 - 时间复杂度O(nlogn),空间复杂度O(1) iteration
3.堆排序 - 时间复杂度O(nlogn),空间复杂度O(n) linked list
所以这里其实只能用#2归并的迭代写法

class Solution:    
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # count the nodes
        n = 0 
        cur = head
        while cur:
            cur = cur.next
            n += 1
            
        dummy = ListNode(-1)
        dummy.next = head
        
        # iterate by length
        i = 1
        while i < n:
            j = 1
            cur = dummy
            # merge two sorted parts
            while i+j <= n:
                p = q = cur.next
                for k in range(i):
                    q = q.next
                x = y = 0
                while x < i and y < i and p and q:
                    if p.val < q.val:
                        cur.next = p
                        p = p.next
                        x += 1
                    else:
                        cur.next = q
                        q = q.next
                        y += 1
                    cur = cur.next
                while x < i and p:
                    cur.next = p
                    p = p.next
                    cur = cur.next
                    x += 1
                while y < i and q:
                    cur.next = q
                    q = q.next
                    cur = cur.next
                    y += 1
                cur.next = q
                j += i*2
            i *= 2
        return dummy.next
        
        
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def merge(self, h1, h2):
        dummy = tail = ListNode(None)
        while h1 and h2:
            if h1.val < h2.val:
                tail.next, h1 = h1, h1.next
            else:
                tail.next, h2 = h2, h2.next
            tail = tail.next
        tail.next = h1 or h2
        return dummy.next
    
    def sortList(self, head):
        if not head or not head.next:
            return head
        slow, fast = head, head
        while fast.next and fast.next.next:
            print(slow.val, fast.val)
            slow, fast = slow.next, fast.next.next
        mid = slow.next
        slow.next = None
        return self.merge(*map(self.sortList, (head, mid)))
        

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值