Sort List —— 歸併排序
阿新 • • 發佈:2019-02-15
問題描述
Sort a linked list in O(n log n) time using constant space complexity.
演算法分析
1、要求時間複雜度為 O(n log n),可以考慮歸併與快排;
2、本文使用歸併,每次將連結串列從中間位置切斷,一分為二;
3、遞迴2過程,直到連結串列長度為1;
4、依次從小到大合併兩個連結串列,最後返回排序好的連結串列。
C++實現
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next ;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode* mergeList(ListNode* head1, ListNode* head2) {
shared_ptr<ListNode> newHead(new ListNode(0));
ListNode* p = newHead.get();
while (head1 && head2) {
if (head1->val <= head2->val) {
p->next = head1;
head1 = head1->next;
}
else {
p->next = head2;
head2 = head2->next;
}
p = p->next;
}
p->next = !head1 ? head2 : head1;
return newHead->next;
}
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next)
return head;
//devide into two lists
ListNode* slow = head,
*fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
slow->next = nullptr;
return mergeList(sortList(head), sortList(fast));
}
};
時間複雜度為O(n*log(n)),空間複雜度為O(1)。