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 };
  • 相关阅读:
    [LeetCode] Min Stack
    [LeetCode] Find Minimum in Rotated Sorted Array
    [LeetCode] Maximum Product Subarray
    [Jobdu] 题目1504:把数组排成最小的数
    [Jobdu] 题目1544:数字序列区间最小值
    Python2.3-原理之语句和语法
    Python2.5-原理之模块
    Vim2.1-Vim简明教程【CoolShell】【非原创】
    Python2.6-原理之类和oop(下)
    QT1.1-与Opencv的hello world
  • 原文地址:https://www.cnblogs.com/easonliu/p/3657107.html
Copyright © 2011-2022 走看看