设为首页 加入收藏

TOP

Leetcode: 23. Merge k Sorted Lists
2017-10-12 18:00:41 】 浏览:9075
Tags:Leetcode: 23. Merge Sorted Lists

Description

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

思路

  • 使用一个优先级队列保存每个链表当前元素值,然后每次取出最小的,将其后的另一个加入队列

代码

  • 时间复杂度。每一个链表平均长度为k,一共有m个链表
  • 最开始建立最小堆的时间为O(mlgm)
  • 然后找的时间:O(mk)*O(lgm),查找时间和调整堆的时间
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    struct cmp{
       bool operator()(const ListNode* a, const ListNode *b){ return a->val > b->val; }  
    };
    
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode *head = NULL, *ptr = NULL, *tmp = NULL;
        priority_queue<ListNode*, vector<ListNode*>, cmp> Queue;
        for(int i = 0; i < lists.size(); ++i){
            if(lists[i])
                Queue.push(lists[i]);
        }
            
        while(!Queue.empty()){
            tmp = Queue.top();
            Queue.pop();
            
            if(tmp->next)
                Queue.push(tmp->next);
                
            if(!head){
                head = ptr = tmp;
            }
            else{
                ptr->next = tmp;
                ptr = ptr->next;
            }
        }
        
        return head;
    }
};
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Leetcode: 22. Generate Parenthe.. 下一篇Leetcode: 24. Swap Nodes in Pai..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目