要求时间复杂度O(nlogn),空间复杂度O(1),参考了题解中的bottom-to-up的归并方法,时间和空间的结果还行
1 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 2 if (l1 == nullptr) 3 return l2; 4 else if (l2 == nullptr) 5 return l1; 6 ListNode* temp1 = l1; 7 ListNode* temp2 = l2; 8 ListNode* next1 = nullptr; 9 ListNode* next2 = nullptr; 10 while (temp1 != nullptr&&temp2 != nullptr) 11 { 12 if (temp1->val <= temp2->val && temp1->next) 13 { 14 if (temp1->next->val > temp2->val) 15 { 16 next2 = temp2->next; 17 temp2->next = temp1->next; 18 temp1->next = temp2; 19 temp2 = next2; 20 temp1 = temp1->next; 21 } 22 else if (temp1->next->val <= temp2->val) 23 temp1 = temp1->next; 24 } 25 else if (temp1->val <= temp2->val && !temp1->next) 26 { 27 temp1->next = temp2; 28 break; 29 } 30 else if (temp1->val > temp2->val) 31 { 32 next2 = temp2->next; 33 temp2->next = temp1; 34 temp1 = temp2; 35 temp2 = next2; 36 l1 = temp1; //bug 37 } 38 } 39 return l1; 40 } 41 ListNode* cut(ListNode* head, int n) 42 { 43 ListNode* temp = head; 44 while (--n&&temp) 45 { 46 temp = temp->next; 47 } 48 if (temp == nullptr) 49 return nullptr; 50 ListNode* res = temp->next; 51 temp->next = nullptr; 52 return res; 53 } 54 ListNode* sortList(ListNode* head) 55 { 56 ListNode* dummy = new ListNode(0); 57 dummy->next = head; 58 int len = 0; 59 ListNode* temp = head; 60 while (temp != nullptr) 61 { 62 len++; 63 temp = temp->next; 64 } 65 ListNode* cur = nullptr; 66 ListNode* left = nullptr; 67 ListNode* right = nullptr; 68 ListNode* tail = nullptr; 69 70 for (int size = 1; size < len; size*=2) 71 { 72 cur = dummy->next; 73 left = cur; 74 tail = dummy; 75 while (cur) 76 { 77 left = cur; 78 right = cut(left, size); 79 cur = cut(right, size); 80 tail->next = mergeTwoLists(left, right); 81 while (tail->next) 82 tail = tail->next; 83 } 84 } 85 return dummy->next; 86 }
不要使用递归,那样空间复杂度一定不是O(1);