zoukankan      html  css  js  c++  java
  • leetcode 23. 合并K个排序链表

    本质上就是用优先队列来做,但是考虑的问题是 如何重载cmp比较函数

    参考网络上的写法

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            auto cmp = [](ListNode* &a, ListNode* &b) {
                return a->val > b->val;
            };
            priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> que(cmp);
    
            for (auto node : lists) 
                if (node)
                    que.push(node);
    
            ListNode *first = new ListNode(-1);
            ListNode *res = first;
            
            while (!que.empty()) {
                ListNode *a = que.top();
                que.pop();
                first->next = a;
                first = first->next;
                if (a->next) 
                    que.push(a->next);
            }
            return res->next;
        }
    };
    
  • 相关阅读:
    NSLocalizedString用法
    4-27学习心得
    手势学习
    plist处理
    数据存储
    initWithFrame方法
    控制器跳转小常识
    UIGestureRecognizer学习笔记
    博客资源
    检测手机wifi有没有打开
  • 原文地址:https://www.cnblogs.com/Draymonder/p/12424682.html
Copyright © 2011-2022 走看看