zoukankan      html  css  js  c++  java
  • 【LeetCode】23. Merge k Sorted Lists

    Merge k Sorted Lists

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

    多路归并。

    1、用make_heap函数维护一个大小为k的最小堆。

    注:由于默认是最大堆,因此需要自定义compare函数。

    注意:comp需要定义为static或者全局函数,因为make_heap、pop_heap、push_heap都是全局库函数。

    2、取出最小元素(即lists[0]),用pop_heap函数将最小元素移到最后

    3、若原lists[0],即当前的lists[last]还有后继结点,则用push_heap将其后继结点调整入堆。

    否则该链表归并完毕,删除。

    重复2、3直到所有链表都归并完毕。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        static bool comp(ListNode* l1, ListNode* l2)
        {
            return l1->val > l2->val;   // min heap
        }
        
        ListNode *mergeKLists(vector<ListNode *> &lists) {
            ListNode* newhead = new ListNode(-1);
            ListNode* tail = newhead;
            //remove empty list first
            vector<ListNode *>::iterator it = lists.begin();
            while(it != lists.end())
            {
                if(*it == NULL)
                    lists.erase(it);
                else
                    it ++;
            }
            
            //init heap
            make_heap(lists.begin(), lists.end(), comp);
            while(!lists.empty())
            {
                //move the min to the end and adjust
                pop_heap(lists.begin(), lists.end(), comp);
                ListNode* curmin = lists[lists.size()-1];
                lists.pop_back();
                if(curmin->next != NULL)
                {
                    lists.push_back(curmin->next);
                    //add the new element to the heap and adjust
                    push_heap(lists.begin(), lists.end(), comp);
                }
                tail->next = curmin;
                tail = tail->next;
                tail->next = NULL;
            }
            return newhead->next;
        }
    };

  • 相关阅读:
    mac redis 安装及基本设置 python操作redis
    mac webstorm自动编译typescript配置
    MySQL数据库的基本操作
    python 面试基础考试题收集
    pyhon 列表的增删改查
    python 文件读取方法详解
    MAC下绕开百度网盘限速下载的方法,三步操作永久生效
    浏览器窗口输入网址后发生的一段事情(http完整请求)
    CMDB
    django适当进阶篇
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4175111.html
Copyright © 2011-2022 走看看