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

    题目链接
    n是总共的数.. k为k个链表
    并且学习了优先队列的比较器如何写......

    /**
     * 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) {
            priority_queue<ListNode*,vector<ListNode*>, cmp> que;
            for(int i=0; i<lists.size(); i++) {
                if(lists[i])
                    que.push(lists[i]);
            }
            ListNode *first = new ListNode(-0x3f3f3f3f);
            ListNode *cur = first;
            while(!que.empty()) {
                ListNode *top = que.top();
                que.pop();
                if(top) {
                    first->next = top;
                    first = first->next;
                    if(first && first->next) {
                        que.push(first->next);
                    }    
                } 
            }
            // first->next = NULL;
            return cur->next;
        }
    };
    
  • 相关阅读:
    2020-03-23
    2020-03-22
    2020-03-21
    2020-03-20
    2020-03-19
    2020-03-18
    2020-03-17
    单元测试-java
    2020-03-16
    C语言拯救计划Day3-1之求一批整数中出现最多的个位数字
  • 原文地址:https://www.cnblogs.com/Draymonder/p/10757280.html
Copyright © 2011-2022 走看看