[python]leetcode(148). Sort List

problem

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

solution

因为常见的排序算法时间复杂度描述的都是顺序表,而链表和顺序表的主要区别就是顺序表可以随机存取,而链表的查找效率为 O(n) ,插入、删除操作链表的效率要更高,但是这建立在已知插入位置的情况下。

class Solution(object):
    def sortList(self, head):

        if not head or not head.next:
            return head

        #divide the pri list into two lists
        pri, slow, fast = head, head, head
        while fast and fast.next:
            pri = slow
            slow = slow.next
            fast = fast.next.next
        pri.next = None

        #sort the two lists
        first = self.sortList(head)
        second = self.sortList(slow)

        #merge and return
        return self.merge(first, second)

    def merge(self, first, second):
        dummy = ListNode(0)
        tail = dummy
        while first and second:
            if first.val < second.val:
                tail.next = first
                tail = tail.next
                first = first.next
            else:
                tail.next = second
                tail = tail.next
                second = second.next

        if first:
            tail.next = first
        else:
            tail.next = second

        return dummy.next

总结

可以把归并排序写成分治的形式,归并排序时间复杂度为 O(nlogn)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值