Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Code:
class Solution { public: ListNode *sortList(ListNode *head) { if(!head) return head; map<int,vector<ListNode *>> sortMap; vector<int> sortVector; ListNode *anchor=new ListNode(0); anchor->next=head; ListNode *cur=head; int n=0; ///////////////// put into map and vector ///////////////// while(cur){ n++; vector<ListNode *> sameValue; sortVector.push_back(cur->val); sortMap[cur->val].push_back(cur); cur=cur->next; } sort(sortVector.begin(),sortVector.end()); // quick-sort costs O(nlogn) ///////////////// reconstruct ///////////////// anchor->next=sortMap[sortVector[0]].front(); for(int j=1,len=sortMap[sortVector[0]].size();j<len;j++) sortMap[sortVector[0]][j-1]->next=sortMap[sortVector[0]][j]; for(int i=1;i<n;i++){ if(sortVector[i-1]!=sortVector[i]){ sortMap[sortVector[i-1]].back()->next=sortMap[sortVector[i]].front(); sortMap.erase(sortVector[i-1]); for(int j=1,len=sortMap[sortVector[i]].size();j<len;j++) sortMap[sortVector[i]][j-1]->next=sortMap[sortVector[i]][j]; } } sortMap[sortVector[n-1]].back()->next=NULL; sortMap.erase(sortVector[n-1]); ////////////////////////////////////////////// head=anchor->next; delete anchor; return head; } };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步