LeetCode - 148. Sort List

148. Sort Listhttps://leetcode.com/problems/sort-list

排列无序列表
要求:时间复杂度O(nlogn),空间复杂度O(1)

排序算法
1.快排 - 时间复杂度O(nlogn),空间复杂度O(logn) recursion
2.归并排序 - 时间复杂度O(nlogn),空间复杂度O(1) iteration
3.堆排序 - 时间复杂度O(nlogn),空间复杂度O(n) linked list
所以这里其实只能用#2归并的迭代写法

class Solution:    
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # count the nodes
        n = 0 
        cur = head
        while cur:
            cur = cur.next
            n += 1
            
        dummy = ListNode(-1)
        dummy.next = head
        
        # iterate by length
        i = 1
        while i < n:
            j = 1
            cur = dummy
            # merge two sorted parts
            while i+j <= n:
                p = q = cur.next
                for k in range(i):
                    q = q.next
                x = y = 0
                while x < i and y < i and p and q:
                    if p.val < q.val:
                        cur.next = p
                        p = p.next
                        x += 1
                    else:
                        cur.next = q
                        q = q.next
                        y += 1
                    cur = cur.next
                while x < i and p:
                    cur.next = p
                    p = p.next
                    cur = cur.next
                    x += 1
                while y < i and q:
                    cur.next = q
                    q = q.next
                    cur = cur.next
                    y += 1
                cur.next = q
                j += i*2
            i *= 2
        return dummy.next
        
        
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def merge(self, h1, h2):
        dummy = tail = ListNode(None)
        while h1 and h2:
            if h1.val < h2.val:
                tail.next, h1 = h1, h1.next
            else:
                tail.next, h2 = h2, h2.next
            tail = tail.next
        tail.next = h1 or h2
        return dummy.next
    
    def sortList(self, head):
        if not head or not head.next:
            return head
        slow, fast = head, head
        while fast.next and fast.next.next:
            print(slow.val, fast.val)
            slow, fast = slow.next, fast.next.next
        mid = slow.next
        slow.next = None
        return self.merge(*map(self.sortList, (head, mid)))
        

你可能感兴趣的:(LeetCode,leetcode,算法,array,sorting,algorithm,链表)