約 2 分鐘316 字209 個單字
題目
原題頁面:https://leetcode.com/problems/sort-list/
題目型別:Linked List, Sort
難度評價:Medium
類似題目:(E) Merge Two Sorted Lists, (M) Sort Colors, (M) Insertion Sort List
Sort a linked list in O(n log n) time using constant space complexity.
分析
連結串列的歸併排序。findMiddle用快慢指標找中點:slow從head出發,fast從head.next出發,fast每次走兩步,slow每次走一步;fast走到頭時slow停在前半段的最後一個節點,偶數個節點時兩半一樣長,奇數個節點時前半段多一個。
mergeList在中點斷開(mid.next = None),兩半分別遞迴呼叫mergeList排好,再像合併兩個有序連結串列那樣合成一條:用一個啞節點new_head當頭,每次取兩邊較小的節點接上,最後把剩下的一段整個接到末尾,返回new_head.next。
時間複雜度是O(n log n):一共log n層,每層找中點和合並加起來是O(n)。空間上,陣列的歸併排序合併時要一個O(n)的輔助陣列,連結串列合併只改next指標,不需要輔助陣列;不過這是自頂向下的遞迴,遞迴棧的深度是log n級別,所以額外空間是O(log n),嚴格說達不到題目要求的常數空間。
要嚴格做到常數空間,得改成自底向上的迭代歸併:先把相鄰的長度為1的段兩兩合併,再按長度2、4、8……合併,不用遞迴,我的程式碼沒有這樣寫。
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution:
def findMiddle(self, head): slow = head fast = head.next while None != fast and None != fast.next: fast = fast.next.next slow = slow.next return slow
def mergeList(self, head): if None == head.next: return head mid = self.findMiddle(head) right_head = mid.next mid.next = None left_list = self.mergeList(head) right_list = self.mergeList(right_head) new_head = ListNode(-1) new_tail = new_head left_node = left_list right_node = right_list while None != left_node and None != right_node: if left_node.val <= right_node.val: new_tail.next = left_node left_node = left_node.next else: new_tail.next = right_node right_node = right_node.next new_tail = new_tail.next new_tail.next = left_node if None != left_node else right_node return new_head.next
def sortList(self, head): if None == head: return None return self.mergeList(head)
|
本文地址:https://xnerv.wang/zh-tw/leetcode-sort-list/