MENU

LeetCode23. Merge k Sorted Lists(链表 / 模拟)

2019 年 09 月 26 日 • 阅读: 2415 • LeetCode阅读设置

LeetCode23. Merge k Sorted Lists(链表 / 模拟)

  • Hard
  • Accepted:456,754
  • Submissions:1,262,052

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

链接

https://leetcode.com/problems/merge-k-sorted-lists

题意

合并k个有序链表。

题解

先会合并两个有序链表:LeetCode21. Merge Two Sorted Lists(链表 / 模拟),然后再转换为每次合并两个链表,直至最后只剩一个链表,具体见代码。

参考:https://leetcode.com/problems/merge-k-sorted-lists/discuss/10531/

代码

  • Runtime: 20 ms, faster than 98.89% of C++ online submissions for Merge k Sorted Lists.
  • Memory Usage: 11.1 MB, less than 67.86% of C++ online submissions for Merge k Sorted Lists.
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int n = lists.size();
        if (n == 0)
            return NULL;
        while (n > 1)
        {
            for (int i = 0; i < n / 2; ++i)
                lists[i] = mergeTwoLists(lists[i], lists[n - 1 - i]);
            n = (n + 1) / 2;
        }
        return lists.front();
    }
    
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
    {
        ListNode* dummy = new ListNode(-1);
        ListNode* cur = dummy;
        while (l1 && l2)
        {
            if (l1->val < l2->val)
            {
                cur->next = l1;
                l1 = l1->next;
            }
            else
            {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        cur->next = (l1 ? l1 : l2);
        return dummy->next;
    }
};

The end.
2019年9月26日 星期四
最后编辑于: 2020 年 04 月 24 日