11.27更新 使用STL优先队列可偷懒,之前没想到
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<int, vector<int>, greater<int>>heap;
for (int i = 0; i < lists.size(); ++i) {
ListNode *p = lists[i];
while (p) {
heap.push(p->val);
p = p->next;
}
}
ListNode *head = new ListNode(-1);
ListNode *p = head;
while (!heap.empty()) {
p->next = new ListNode(heap.top());
p = p->next;
heap.pop();
}
return head->next;
}
};
想了两种方法,结果应该都是(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;
}
}
};