LeetCode Medium 148 連結串列排序 Python
阿新 • • 發佈:2018-12-31
def sortList(self, head): """ 暴力解法,將node都取出來然後重新拼接 """ nodes = [] while head != None: nodes.append(head) the_next = head.next head.next = None head = the_next nodes.sort(key=lambda x: x.val) dummy = ListNode(0) p = dummy for node in nodes: p.next = node p = p.next return dummy.next def sortList1( head): """ My MergeSortMethod 演算法:歸併排序 思路: 分而治之 將連結串列劃分為左右兩個部分,然後對左右兩個部分不停地劃分直到剩下單個元素,就好排序了,排完後進行合併, 也就是有序連結串列合併,就可以完成排序了 要注意mid_pre 用快慢指標走的話,slow的位置將是1,而歸併要一分為二,mid應該在2那個位置,所以用mid_pre滯後記錄slow的前一個位置, 是要分割用的mid位置 連結串列:4-->2-->1-->3-->None, ^ ^ | | slow fast 複雜度分析: 時間:NLOGN 空間:O1,不考慮遞迴棧的話 """ def merge_sort(left, right): if left == None: return right if right == None: return left dummy = ListNode(0) p = dummy while left and right: if left.val <= right.val: p.next = left left = left.next else: p.next = right right = right.next p = p.next if left != None: p.next = left if right != None: p.next = right return dummy.next def merge(head): if head == None or head.next == None: return head fast = slow = head mid_pre = None while fast and fast.next: mid_pre = slow slow = slow.next fast = fast.next.next right_head = mid_pre.next mid_pre.next = None left = merge(head) right = merge(right_head) return merge_sort(left, right) return merge(head) def sortList2(self, head): """ Disscussion QuickSort 演算法:快排 思路: 快排的連結串列寫法,要注意一些dummy節點的運用,以及記錄pre和post等 複雜度分析: 時間:NLOGN 空間:01,不考慮遞迴棧的話 """ def partition(start, end): node = start.next.next pivotPrev = start.next pivotPrev.next = end pivotPost = pivotPrev while node != end: temp = node.next if node.val > pivotPrev.val: node.next = pivotPost.next pivotPost.next = node elif node.val < pivotPrev.val: node.next = start.next start.next = node else: node.next = pivotPost.next pivotPost.next = node pivotPost = pivotPost.next node = temp return [pivotPrev, pivotPost] def quicksort(start, end): if start.next != end: prev, post = partition(start, end) quicksort(start, prev) quicksort(post, end) newHead = ListNode(0) newHead.next = head quicksort(newHead, None) return newHead.next