论坛首页 编程语言技术论坛

[LeetCode] Merge k Sorted Lists

浏览 1193 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-04-23  

 

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
bool cmp(const ListNode* a, const ListNode* b) {
    return a->val > b->val;
}
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        ListNode* head, *cur;
        auto it = remove_if(lists.begin(), lists.end(), [](const ListNode* a) {return a == NULL;});
        lists.erase(it, lists.end());
        make_heap(lists.begin(), lists.end(), cmp);
        if (lists.size() == 0) return NULL;
        pop_heap(lists.begin(), lists.end(), cmp);
        auto end = lists.end() - 1;
        head = *end;
        *end = head->next;
        if (*end == NULL) {
            lists.erase(lists.end()-1);
        } else {
            push_heap(lists.begin(), lists.end(), cmp);
        }
        cur = head;
        while (!lists.empty()) {
            pop_heap(lists.begin(), lists.end(), cmp);
            auto end2 = lists.end() - 1;
            cur->next = *end2;
            cur = cur->next;
            *end2 = cur->next;
            if (*end2 == NULL) {
                lists.erase(lists.end()-1);
            } else {
                push_heap(lists.begin(), lists.end(), cmp);
            }
        }
        return head;
    }
};

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics