【LeetCode 中等题】70-排序链表

题目描述:在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4

示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

解法1。归并排序的递归做法,先找到链表的中点,然后从中间断开,然后对前半段和后半段进行归并排序,断开这个操作是用递归,对前半段递归到底,回溯到倒数第二层,再对后半段递归到底,再调用merge函数。

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        slow = head
        pre = head
        fast = head
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
          
        '''      
        l = sortList(head)
        r = sortList(slow)
        return self.merge(l, r)
        '''
        # 上面这段等价于:
        return self.merge(self.sortList(head), self.sortList(slow))
    
    def merge(self, l1, l2):
        if not l1:
            return l2
        if not l2:
            return l1
        if l1.val < l2.val:
            l1.next = self.merge(l1.next, l2)
            return l1
        else:
            l2.next = self.merge(l1, l2.next)
            return l2

解法2。其实是在上述做法的基础上把merge函数改写成了用循环做,效率提高了不少

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        slow = head
        pre = head
        fast = head
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
        return self.merge(self.sortList(head), self.sortList(slow))
    
    def merge(self, l1, l2):
        if not l1:
            return l2
        if not l2:
            return l1
        dummy = ListNode(0)
        cur = dummy
        while l1 and l2:
            if l1.val < l2.val:
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        if l1:
            cur.next = l1
        if l2:
            cur.next = l2
        return dummy.next

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/86305138
今日推荐