8.10 练手 腾讯50题 148

Leetcode 148. Sort List

单向链表排序,O(nLog(n))的时间复杂度和常数的空间复杂度。

因为常数的空间复杂度不能另外开数组排序或者链表比较。

O(nLog(n))说明应该用的不是冒泡插入等,可能是归并或者快排。

解法一:归并排序.

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        
       # middleNode = self.getMid(head)
        fast, slow =head.next, head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        middleNode = slow.next
        slow.next = None # PAY ATTENTION!!
        left = self.sortList(head)
        right = self.sortList(middleNode)
        return self.mergeList(left, right)
        
    #def getMid(self, head):
    #    f = head
    #    slow = head
    #    middle = None
    #    while(f.next == None):
    #        middle = slow
    #        slow = slow.next
    #        f = f.next.next
    #    middle = slow.next
    #    slow.next = None
    #    return middle
    
    def mergeList(self, l, r):
        if not r or not l:
            return r or l
        tempHead = ListNode(0)
        cur = tempHead
        while(l != None and r != None):
            if(l.val <= r.val):
                cur.next = l
                cur = cur.next
                l = l.next
            else:
                cur.next = r
                cur = cur.next
                r = r.next
        if (l != None):
            cur.next = l
        if (r != None):
            cur.next = r
        return tempHead.next

中间有个步骤可以直接写,不用另外写成函数,注意细节,不然可能会Time Excess.

 

解法二:快排

https://leetcode.com/problems/sort-list/discuss/46827/Python-quick-sort-solution-easy-to-understand-beats-95.51

参考别人的解法,想法是设置了两个Pivot其中一个记录前一位,这样就不需要双向链表了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值