zoukankan      html  css  js  c++  java
  • [Leetcode] Merge k Sorted Lists

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

    no comment.

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *getNext(vector<ListNode *> &lists) {
    12         ListNode *next = NULL;
    13         int min = INT_MAX;
    14         int idx = 0;
    15         for (int i = 0; i < lists.size(); ++i) {
    16             if (lists[i] != NULL && lists[i]->val < min) {
    17                 min = lists[i]->val;
    18                 idx = i;
    19                 next = lists[i];
    20             }
    21         }
    22         if (lists[idx] != NULL) lists[idx] = lists[idx]->next;
    23         return next;
    24     }
    25     ListNode *mergeKLists(vector<ListNode *> &lists) {
    26         if (lists.size() < 1) return NULL;
    27         ListNode *res = new ListNode(-1);
    28         ListNode *pos = res;
    29         while(pos != NULL) {
    30             pos->next = getNext(lists);
    31             pos = pos->next;
    32         }
    33         return res->next;
    34     }
    35 };

     现在LeetCode更新的测试样例,上面的算法会超时。可以使用一个堆来优化。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 struct cmp {
    10     bool operator () (ListNode* a, ListNode* b) {
    11         return a->val > b->val;
    12     }
    13 };
    14 
    15 class Solution {
    16 public:
    17     ListNode* mergeKLists(vector<ListNode*>& lists) {
    18         ListNode dummy(0);
    19         ListNode *p = &dummy;
    20         priority_queue<ListNode*, vector<ListNode*>, cmp> heap;
    21         for (auto &list : lists) {
    22             if (list) heap.push(list);
    23         }
    24         for ( ; !heap.empty(); heap.pop()) {
    25             auto u = heap.top();
    26             p->next = u;
    27             p = p->next;
    28             if (u->next) heap.push(u->next);
    29         }
    30         return dummy.next;
    31     }
    32 };
  • 相关阅读:
    性能测试基本功 手动配置nginx+phpcgi+zend+mysql
    MySQL的show full processlist命令
    LoadRunner测试Webservices的例子
    Firefox 5 公开测试下载
    Shunra 即将发布 PerformanceSuite 7.0 和NetworkCatcher 7.0
    LoadRunner常见问题
    动态生成的图片保存成png格式
    如何解决ASP.NET程序安装到繁体系统上的乱码问题
    在Ubuntu上下载、编译和安装Android最新源代码
    腾讯微博api的蛋疼问题
  • 原文地址:https://www.cnblogs.com/easonliu/p/3657107.html
Copyright © 2011-2022 走看看