• [LeetCode] 23


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

    /**
    * 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) {
        if (lists.empty()) {
          return nullptr;
        }
        auto comp_func = [](ListNode* a, ListNode* b){ return (a->val >= b->val);};
        vector<ListNode*> heap;
        for (auto node : lists) {
          if (node) {
            heap.emplace_back(node);
          }
        }
        ListNode head_node(-1);
        ListNode *head = &head_node;
        make_heap(heap.begin(), heap.end(), comp_func);

        while (!heap.empty()) {
          pop_heap(heap.begin(), heap.end(), comp_func);
          auto &node = heap.back();
          heap.pop_back();
          head->next = node;
          head = node;
          if (node->next) {
            heap.emplace_back(node->next);
            push_heap(heap.begin(), heap.end(), comp_func);
          }
        }
        return head_node.next;
      }
    };

  • 相关阅读:
    ios属性或者变量的前缀-杂记
    xcode注释方法
    ios 不同的数据类型转化为json类型
    第一部分----HTML的基本结构与基本标签
    Git使用总结
    c#后台弹出框
    svn下载安装
    svn配置
    access 日期转换
    C# 中关于汉字与16进制转换的代码
  • 原文地址:https://www.cnblogs.com/shoemaker/p/4769379.html
Copyright © 2020-2023  润新知