题解 | 合并k个已排序的链表

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <algorithm>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 可以利用现有
     * 
     * @param lists ListNode类vector 
     * @return ListNode类
     */

    static bool compareLess(ListNode* l1, ListNode* l2) {
        return l1->val > l2->val;
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        // write code here
        ListNode fake(0);
        ListNode *cur = &fake;

        vector<ListNode*> vec;

        for  (auto & item : lists) {
            if (item) {
                vec.emplace_back(std::move(item));
            }
        }
        make_heap(vec.begin(), vec.end(), compareLess);

        while(vec.size()) {
            cur->next = vec.front();
            pop_heap(vec.begin(), vec.end(), compareLess);
            vec.pop_back();
            cur = cur->next;
            if (cur->next) {
                vec.push_back(cur->next);
                push_heap(vec.begin(), vec.end(), compareLess);
            }
        }
        return fake.next;
    }
};

全部评论

相关推荐

挣K存W养DOG:我记得好多人说这个公司就是白嫖方案的,现在有大体方案要让你给他展示实现细节了,也是无敌了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务