码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 23 - Merge k Sorted Lists

时间:2015-08-29 18:33:58      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

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) {}
* };
*/
class Solution {
public:
  ListNode* mergeKLists(vector<ListNode*>& lists) {
    if (lists.empty()) {
      return nullptr;
    }
    auto comp_func = [](ListNode* a, ListNode* b){ return (a->val >= b->val);};
    vector<ListNode*> heap;
    for (auto node : lists) {
      if (node) {
        heap.emplace_back(node);
      }
    }
    ListNode head_node(-1);
    ListNode *head = &head_node;
    make_heap(heap.begin(), heap.end(), comp_func);

    while (!heap.empty()) {
      pop_heap(heap.begin(), heap.end(), comp_func);
      auto &node = heap.back();
      heap.pop_back();
      head->next = node;
      head = node;
      if (node->next) {
        heap.emplace_back(node->next);
        push_heap(heap.begin(), heap.end(), comp_func);
      }
    }
    return head_node.next;
  }
};

 

[LeetCode] 23 - Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/shoemaker/p/4769379.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!