Crack LeetCode 之 148. Sort List
阿新 • • 發佈:2018-12-16
https://leetcode.com/problems/sort-list/
對於連結串列的排序,非常適合用歸併排序演算法。但本題還要求只用O(1)的記憶體空間;如果考慮歸併演算法的棧的話,實際上本題的解法使用的是O(n)的記憶體空間。所以本題解法的時間複雜度是O(n Log(n)),空間複雜度是O(n)。其實歸併排序也可以使用遍歷的方法實現,每次遍歷使用不同的步長即可,但是本人懶得修改了~~
C++程式碼如下:
class Solution { public: ListNode * sortList(ListNode * head) { if(head == NULL || head->next == NULL) return head; ListNode * walker = head; ListNode * runner = head; while(runner->next!=NULL && runner->next->next!=NULL) { walker = walker->next; runner = runner->next->next; } ListNode * head2 = walker->next; walker->next = NULL; ListNode * head1 = head; head1 = sortList(head1); head2 = sortList(head2); return merge(head1, head2); } ListNode * merge(ListNode * head1, ListNode * head2) { ListNode * helper = new ListNode(0); helper->next = head1; ListNode * pre = helper; while(head1!=NULL && head2!=NULL) { if(head1->val<head2->val) head1 = head1->next; else { ListNode * next = head2->next; head2->next = pre->next; pre->next = head2; head2 = next; } pre = pre->next; } if(head2!=NULL) pre->next = head2; return helper->next; } };
Python程式碼如下:
class Solution: def sortList(self, head): if head == None or head.next == None: return head walker = head runner = head while runner.next != None and runner.next.next != None: walker = walker.next runner = runner.next.next head2 = self.sortList(walker.next) walker.next = None head1 = self.sortList(head) return self.merge(head1, head2) def merge(self, head1, head2): if head1 == None: return head2 if head2 == None: return head1 helper = ListNode(0) helper.next = head1 pre = helper while head1 != None and head2 != None: if head1.val < head2.val: head1 = head1.next else: next = head2.next head2.next = head1 pre.next = head2 head2 = next pre = pre.next if head2 != None: pre.next = head2 return helper.next