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

[leetcode]Merge k Sorted Lists

时间:2014-12-18 23:31:27      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

use smaller heap

 

/**
 * 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) {
        priority_queue<ListNode*, vector<ListNode*>, function<bool(ListNode*, ListNode*)> > 
            que([&](ListNode* a, ListNode* b) {return a->val > b->val;});
        for (int i = 0; i < lists.size(); i++) {
            if (lists[i]) que.push(lists[i]);
        }
        ListNode* dummy = new ListNode(-1);
        ListNode* curr = dummy;
        while(!que.empty()) {
            curr->next = que.top();
            curr = curr->next;
            que.pop();
            if (curr->next) {
                que.push(curr->next);
            }
            curr->next = nullptr;
        }
        return dummy->next;
    }
};

 

[leetcode]Merge k Sorted Lists

标签:style   blog   io   color   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/x1957/p/4172796.html

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