跟着专注于计算机视觉的AndyJ的妈妈我学算法之每日一题leetcode148排序链表

排序链表,时间复杂度要求是 O ( n l o g n ) O(nlogn) ,又是链表,想到归并排序。
可以回顾下如果是array如何归并排序。同理借鉴到链表就好了。递归。
好了,题:

148. 排序链表
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

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

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

直接归并,注释一下,方便读吧。
代码:

class Solution:
    # 时间复杂度O(nlogn),用归并排序
    def sortList(self, head: ListNode) -> ListNode:
        if not head:
            return None
        if not head.next:
            return head

		# 找中点;举个只有两个节点的例子,就知道为什么是判断fast.next.next了
        slow = head
        fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        
        pre = head
        mid = slow.next
        slow.next = None
        # 递归,写清楚当下解决什么问题,未来的问题,交给递归
        left = self.sortList(pre)
        right = self.sortList(mid)
        # 返回left,right,希望是排好序的,然后再进行merge
        rethead = self.merge(left, right)
        return rethead
    
    def merge(self, left, right):
    	# merge操作,正常操作
        nhead = ListNode(None)
        rethead = nhead
        while left and right:
            if left.val < right.val:
                nhead.next = left
                nhead = nhead.next
                left = left.next
            else:
                nhead.next = right
                nhead = nhead.next
                right = right.next
        if not left:
            nhead.next = right
        if not right:
            nhead.next = left
        return rethead.next

好了。

猜你喜欢

转载自blog.csdn.net/mianjiong2855/article/details/107468354
今日推荐