Sort a linked list in O(n log n) time using constant space complexity.
思路:题目要求O(n log n)的时间复杂度以及常空间复杂度,因此,使用归并排序策略。
1 class Solution { 2 public: 3 ListNode *sortList( ListNode *head ) { 4 if( !head || !head->next ) { return head; } 5 if( !head->next->next ) { 6 if( head->val > head->next->val ) { 7 int temp = head->val; 8 head->val = head->next->val; 9 head->next->val = temp; 10 } 11 return head; 12 } 13 ListNode *slow = head, *fast = head->next; 14 while( fast->next ) { 15 slow = slow->next; 16 fast = fast->next; 17 if( fast->next ) { fast = fast->next; } 18 } 19 fast = slow->next; slow->next = 0; 20 slow = sortList( head ); 21 fast = sortList( fast ); 22 return merge( slow, fast ); 23 } 24 private: 25 ListNode *merge( ListNode *slow, ListNode *fast ) { 26 if( !slow ) { return fast; } 27 if( !fast ) { return slow; } 28 ListNode *head = 0, *end = 0; 29 if( slow->val <= fast->val ) { 30 head = end = slow; slow = slow->next; 31 } else { 32 head = end = fast; fast = fast->next; 33 } 34 while( slow && fast ) { 35 if( slow->val <= fast->val ) { 36 end->next = slow; 37 end = end->next; 38 slow = slow->next; 39 } else { 40 end->next = fast; 41 end = end->next; 42 fast = fast->next; 43 } 44 } 45 if( slow ) { end->next = slow; } 46 else { end->next = fast; } 47 return head; 48 } 49 };
时间: 2024-10-26 06:01:50