2013.12.7 01:32
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution:
You must've done the job of merging two sorted linked lists quite often, this time it's k lists. The simple way is to find the smallest of all k head nodes, pick it out and put into the result list, then move the corresponding node forward by 1 step. Do this until all k lists are empty.
In that case, the time complexity would be O(n * k), where $n is the total number of nodes in k lists. Every time we use linear search through k nodes to find the minimum, that's where the problem lies.
With minimal heap we can achieve O(n * log(k)) time, with O(k) extra space complexity. But note that you cannot put a pointer into the priority_queue STL, so might as well use some trick to deal with this trivial matter, e.g. a wrapper struct or class will do.
Accepted code:
1 // 9CE, 1WA, 1AC, pointer can't be elements of priority_queue, might as well wrap it with a class. 2 // Seem so silly... 3 #include <queue> 4 using namespace std; 5 /** 6 * Definition for singly-linked list. 7 * struct ListNode { 8 * int val; 9 * ListNode *next; 10 * ListNode(int x) : val(x), next(NULL) {} 11 * }; 12 */ 13 14 class ListNodeSt{ 15 public: 16 ListNode *ptr; 17 18 ListNodeSt(ListNode *_ptr = nullptr){ 19 ptr = _ptr; 20 } 21 }; 22 23 bool operator < (const ListNodeSt a, const ListNodeSt b) { 24 return a.ptr->val > b.ptr->val; 25 } 26 27 class Solution { 28 public: 29 ListNode *mergeKLists(vector<ListNode *> &lists) { 30 // IMPORTANT: Please reset any member data you declared, as 31 // the same Solution instance will be reused for each test case. 32 int k; 33 ListNode *root, *par, *tmp; 34 ListNodeSt st; 35 36 while(!pq.empty()){ 37 pq.pop(); 38 } 39 k = lists.size(); 40 if(k <= 0){ 41 return nullptr; 42 } 43 44 45 int i; 46 for(i = 0; i < k; ++i){ 47 if(lists[i] != nullptr){ 48 pq.push(ListNodeSt(lists[i])); 49 } 50 } 51 root = nullptr; 52 par = root; 53 while(!pq.empty()){ 54 st = pq.top(); 55 tmp = st.ptr; 56 pq.pop(); 57 if(par == nullptr){ 58 par = tmp; 59 root = par; 60 }else{ 61 par->next = tmp; 62 } 63 if(tmp->next != nullptr){ 64 pq.push(ListNodeSt(tmp->next)); 65 } 66 tmp->next = nullptr; 67 par = tmp; 68 } 69 70 return root; 71 } 72 private: 73 priority_queue<ListNodeSt> pq; 74 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)