• 【LeetCode】023. Merge k Sorted Lists


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

    题解:

      归并思想。

    Solution 1

     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* mergeKLists(vector<ListNode*>& lists) {
    12         int n = lists.size();
    13         if (n < 1)
    14             return nullptr;
    15         
    16         for (int i = 1; i < n ; i *= 2) {
    17             int len = i;
    18             for (int j = 0; j + len < n; j += 2 *len) {
    19                 lists[j] = mergeTwoLists(lists[j], lists[j + len]);
    20             }
    21         }
    22         
    23         return lists[0];
    24     }
    25     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
    26         ListNode dummy(-1);
    27         ListNode *cur = &dummy;
    28         while (l1 && l2) {
    29             if (l1->val < l2->val) {
    30                 cur->next = l1;
    31                 l1 = l1->next;
    32             } else {
    33                 cur->next = l2;
    34                 l2 = l2->next;
    35             }
    36             cur = cur->next;
    37         }
    38         cur->next = l1 ? l1 : l2;
    39         
    40         return dummy.next;
    41     }
    42 };

    Solution 2

      利用最小堆,c++的优先队列priority_queue。

     1 class Solution {  
     2 public:  
     3     struct cmp {
     4         bool operator () (ListNode *a, ListNode *b) {
     5             return a->val > b->val;
     6         }
     7     };
     8     ListNode *mergeKLists(vector<ListNode *> &lists) {  
     9         priority_queue<ListNode*, vector<ListNode*>, cmp> q;
    10         for (auto list : lists) {
    11             if (list)  
    12                 q.push(list);
    13         }
    14         
    15         ListNode *head = NULL, *pre = NULL, *tmp = NULL;
    16         while (!q.empty()) {
    17             tmp = q.top();
    18             q.pop();
    19             if (!pre) 
    20                 head = tmp;
    21             else 
    22                 pre->next = tmp;
    23             pre = pre->next;
    24             // 此节点所在数组仍有元素,则添加进最小堆中
    25             if (tmp->next) 
    26                 q.push(tmp->next);
    27         }
    28         return head;
    29     }  
    30 };

    转自:Grandyang

  • 相关阅读:
    C语言I博客作业08
    博客作业6
    C语言I博客作业05
    C语言I博客作业03
    5.C#2.0之不完整类型(完成)
    4.C#2.0之迭代器(完成)
    3.C#2.0之匿名方法(完成)
    2.C#2.0之泛型(完成)
    1.C#2.0之2.0简介(完成)
    18.C#基础之不安全代码(完成)
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8647235.html
Copyright © 2020-2023  润新知