LeetCode148. SortList

题目描述:

Sort a linked list in O(n log n) time using constant space complexity.

解题思路:

排序不难,难的是在题目给定的条件下进行排序。

首先想到快排序。无奈发现单链表中交换元素很麻烦,放弃这个思路。接着想到归并排序,单链表中划分两个区域,归并,都很方便。

自顶向下的归并排序,空间复杂度为log(n)(n为链表长度)。于是想到自底向上归并排序,由于是用循环写的,空间复杂度为O(C),满足题目要求。

解题代码:

class Solution(object):
    def sortList(self, head):
        if not head or not head.next:
            return head
        cur, length = head, 0
        while cur:
            length +=1
            cur = cur.next
        dummy = ListNode(0)
        dummy.next = head
        step = 1
        while step < length:
            tail, cur = dummy, dummy.next
            while cur:
                left, cur = self.split(cur, step)
                right, cur = self.split(cur, step)
                tail = self.merge(left, right, tail)
            step *= 2
        return dummy.next

    def split(self, cur, step):
        node = cur
        while cur and step > 1:
            cur = cur.next
            step -= 1
        if cur:
            tmp = cur.next
            cur.next = None
            cur = tmp
        return node, cur

    def merge(self, left, right, tail):
        while left and right:
            if left.val < right.val:
                tail.next = left
                tail, left = tail.next, left.next
            else:
                tail.next = right
                tail, right = tail.next, right.next
        if left:
            tail.next = left
        if right:
            tail.next = right
        while tail.next:
            tail = tail.next
        return tail

小结:

除了快排序,归并排序也很实用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值