标签:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
本题是多链表融合,可以选择利用归并算法思想,两两链表融合后再归并,也可以一起融合。本文是一起融合的想法,利用最小堆,每次选取最小的元素。424ms
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: struct CompareListElement { bool operator ()(const ListNode* a, const ListNode* b) const{ return (a->val > b->val); } }; ListNode *mergeKLists(vector<ListNode *> &lists) { vector<ListNode*> vecK; ListNode* dummyHead = new ListNode(0); ListNode* tail = dummyHead; for (vector<ListNode *>::size_type i = 0; i < lists.size(); ++i) { if (lists[i] != NULL) { vecK.push_back(lists[i]); } } std::make_heap(vecK.begin(), vecK.end(), CompareListElement()); while (!vecK.empty()) { tail->next = vecK.front(); tail = tail->next; std::pop_heap(vecK.begin(), vecK.end(), CompareListElement()); vecK.pop_back(); if (tail->next != NULL) { vecK.push_back(tail->next); std::push_heap(vecK.begin(), vecK.end(), CompareListElement()); } } return dummyHead->next; } };
[LeetCode] #23 Merge k Sorted Lists
标签:
原文地址:http://www.cnblogs.com/Scorpio989/p/4545904.html