首页 > 代码库 > 023. Merge k Sorted Lists

023. Merge k Sorted Lists

方法一:时间复杂度O(m1 + m2 + .. m2),超时

 1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     ListNode* mergeKLists(vector<ListNode*>& lists) {
       // 注意这里的判空情况[[]]
12 // 寻找最小值节点13 ListNode* ptr = nullptr;14 ListNode* pHead = ptr;15 if (lists.size() == 0) return pHead;16 else {17 int minIndex = -1;18 for (int i = 0; i < lists.size(); ++i) {19 if (lists[i] != nullptr) {20 if (minIndex == -1) minIndex = i;21 else {22 if (lists[i]->val < lists[minIndex]->val) minIndex = i;23 }24 }25 }26 if (minIndex != -1) {27 ptr = lists[minIndex];28 lists[minIndex] = lists[minIndex]->next;29 }30 //cout << ptr->val << endl;31 pHead = ptr; // 头指针32 bool flag = false; // 判断是否所有的点都已经排序33 while (!flag) {34 flag = true;35 int index = -1; // 记录最小节点下标36 for (int i = 0; i < lists.size(); ++i) {37 if (lists[i] != nullptr) {38 flag = false;39 if (index == -1) index = i;40 else {41 if (lists[i]->val < lists[index]->val) index = i;42 }43 }44 }45 46 if (index != -1) {47 //cout << lists[index]->val << endl;48 ptr->next = lists[index];49 ptr = ptr->next;50 lists[index] = lists[index]->next;51 }52 }53 return pHead;54 }55 }56 };

 

方法二:

023. Merge k Sorted Lists