zoukankan      html  css  js  c++  java
  • [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;
      }
    };

  • 相关阅读:
    webpack进阶(二)
    webpack的loader和plugin的区别
    接口和面向接口编程
    设计原则与编程技巧汇总
    W3C的盒子模型和IE的盒子模型
    React的组件
    React的路由react-router
    三种编程命名规则:驼峰命名法,帕斯卡命名法,匈牙利命名法
    gulp 构建 demo
    antd 表单的两种校验方式
  • 原文地址:https://www.cnblogs.com/shoemaker/p/4769379.html
Copyright © 2011-2022 走看看