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

LeetCode 023 Merge k Sorted Lists

时间:2015-02-07 17:19:56      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

题目要求:Merge k Sorted Lists

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

 

分析:

参考网址:http://blog.csdn.net/a83610312/article/details/8554241

思路是:首先将k个链表的第一个节点集合,建堆,然后取出堆顶的节点,链接到结果链表上,然后将该节点的下一个节点入堆,直到所有链表都已经完成;

下面的Node结构体好像根本无必要,刚开始没注意是链表(而链表可以很方便的获取下一个节点,如果是数组的话还得记录它来自哪个数组);

有两点需要注意:

1.当一条链表结束的时候,添加值为INF的新Node加入堆,可以方便地避免NULL的判断;

2.make_heap()默认是大顶堆,所以要显示指定使用greater<node>(),来获取小顶堆;

 

代码如下:

#define INF 1000000

struct node{
    
    int val;
    ListNode* from;
    
    node(ListNode* n){
        if(n == NULL) val = INF;
        else val = n->val;
        from = n;
    }

    bool operator<(const node& other)const{
        return val<other.val;
    }
    
    bool operator>(const node& other)const{
        return val>other.val;
    }
};
    
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if (lists.empty()) return NULL;
        int n = lists.size();
        vector<node> heap;
        heap.reserve(n);
        
        for(int i = 0; i < n; i++)
            heap.push_back(node(lists[i]));
            
        make_heap(heap.begin(), heap.end(),greater<node>());
        ListNode* head= new ListNode(0);
        ListNode* pL = head;
        pop_heap(heap.begin(), heap.end(),greater<node>());
        node small = heap.back();
        heap.pop_back();
        
        while(small.val!=INF){
            
            ListNode* next=small.from->next;
            pL->next=small.from;
            small.from->next=NULL;
            pL=pL->next;
    
            heap.push_back(node(next));
            push_heap(heap.begin(), heap.end(),greater<node>());
            pop_heap(heap.begin(), heap.end(),greater<node>());
            small=heap.back();
            heap.pop_back();
        }
    
        ListNode* ret=head->next;
        delete head;
        return ret;    
        
    }
};

 

LeetCode 023 Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/510602159-Yano/p/4278953.html

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