1. 程式人生 > >23 Merge k Sorted Lists

23 Merge k Sorted Lists

想了兩種方法,結果應該都是(n^2)我就選了一個感覺舒服一點的,定義一個指標集,然後像< 21 Merge Two Sorted Lists>裡一樣移動

/**
 * 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) { int n = lists.size(); ListNode *q[10000]; ListNode* current=NULL, *k; if (lists.empty())return current; for (int i = 0; i < n; ++i) { q[i] = lists[i]; } current = new ListNode(0); k = new ListNode(0); current->next = k; int record_i; int minn; while (1) { minn =
1 << 31 - 1; for (int i = 0; i < n; ++i) { if (q[i] == NULL)continue; if (q[i]->val < minn) { minn = q[i]->val; record_i = i; } } if (minn == 1 << 31 - 1) { k->next = NULL; return current->next->next; } k->next = new ListNode(q[record_i]
->val); k = k->next; q[record_i] = q[record_i]->next; } } };