题解 | 合并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*> data;
        for (const auto& item : lists) {
            if (item) {
                data.push_back(item);
            }
        }

        make_heap(data.begin(), data.end(), compareLess);

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


        return fake.next;
    }
};

全部评论

相关推荐

xxxxOxo:该催就催,想要你的不会因为催就挂,催了就挂的是因为本来就要挂你
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务