题目
字节面试题
复杂度分析
时间复杂度O(nlogn) 空间复杂度为O(1)
解题思路参照官方做法2:自底向上归并排序 这里给出注释版,便于本次和以后做这题的理解 cpp代码
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==nullptr) return head;
int length = 0;
ListNode* node = head;
while(node!=nullptr){
length++;
node = node->next;
}
ListNode * dummyHead = new ListNode(0);
dummyHead->next = head;
for(int subLen=1;subLen<length;subLen=subLen*2){
ListNode* prev = dummyHead;
ListNode* curr = dummyHead->next;
while(curr!=nullptr){
ListNode* head1 = curr;
for(int i=1;i<subLen&&curr!=nullptr&&curr->next!=nullptr;i++){
curr = curr->next;
}
ListNode* head2 = curr->next;
curr->next = nullptr;
curr = head2;
for(int i=1;i<subLen&&curr!=nullptr&&curr->next!=nullptr;++i){
curr = curr->next;
}
ListNode* next = nullptr;
if(curr!=nullptr){
next = curr->next;
curr->next = nullptr;
}
ListNode* merged = mergeTwoLists(head1,head2);
prev->next = merged;
while(prev->next!=nullptr){
prev = prev->next;
}
curr = next;
}
}
return dummyHead->next;
}
ListNode* mergeTwoLists(ListNode* l1,ListNode* l2){
ListNode* dummy = new ListNode(0);
ListNode* curr = dummy;
while(l1!=nullptr && l2!=nullptr){
if(l1->val < l2->val){
curr->next = l1;
l1 = l1->next;
}else{
curr->next = l2;
l2 = l2->next;
}
curr = curr->next;
}
if(l1==nullptr) curr->next = l2;
if(l2==nullptr) curr->next = l1;
return dummy->next;
}
};
|