首页 > 代码库 > Merge k Sorted Lists
Merge k Sorted Lists
Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
根据k个已经排好序的链表构造一个排序的链表,采用类似归并排序的算法可以通过测试
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.empty()) return nullptr; return helper(lists, 0 , lists.size()-1); } private: ListNode* merge(ListNode* left, ListNode* right){ ListNode* head = new ListNode(0); ListNode* last = head; while(left && right){ if(left->val < right->val){ last->next = left; left = left->next; } else{ last->next = right; right = right->next; } last = last->next; } last->next = (left==nullptr)? right: left; return head->next; } ListNode* helper(vector<ListNode*>& lists, int start, int end){ cout << start << " "<<end <<endl; if(start == end) return lists[start]; else if (start+1 ==end){ return merge(lists[start], lists[end]); } ListNode* left = helper(lists, start, start+(end-start)/2); ListNode* right = helper(lists, start + (end - start) / 2 + 1, end); return merge(left,right); } };
Merge k Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。