zoukankan      html  css  js  c++  java
  • Leetcode: 23. Merge k 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;
        }
    };
    
  • 相关阅读:
    Lambda
    Guava
    创建数据库时报错 'str' object has no attribute 'decode'
    服务器并发测试(jmeter)
    Mosquitto 创建用户自动输入密码
    menuconfig 语法与用法
    Django操作mongodb
    mqtt mosquitto 安装与使用
    python 使用mongodb数据库
    djangorestframework token 认证
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6822688.html
Copyright © 2011-2022 走看看