【leetcode】23. Merge k Sorted Lists

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tianxieeryang/article/details/86530782

Problem

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

Solution

用到 【leetcode】21. Merge Two Sorted Lists

1、Python (124 ms, faster than 61.75% )

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if len(lists) == 0:
            return None
        if len(lists) == 1:
            return lists[0]
        head1 = self.mergeKLists(lists[:len(lists) / 2])
        head2 = self.mergeKLists(lists[len(lists) / 2:])
        return self.mergeTwoLists(head1, head2)
    
    def mergeTwoLists(self, l1, l2):
        if not l1: return l2
        if not l2: return l1
        head = ListNode(0)
        p = head
        while l1 and l2:
            if l1.val <= l2.val:
                p.next, l1 = l1, l1.next
            else:
                p.next, l2 = l2, l2.next
            p = p.next
        if l1: p.next = l1
        if l2: p.next = l2
        return head.next

2、C (12 ms, faster than 73.70%)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoList(struct ListNode* l1, struct ListNode* l2) {
    if (l1 == NULL)    return l2;
    if (l2 == NULL)    return l1;
    struct ListNode* head = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode* p = head;
    while (l1 && l2) {
        p->next = (struct ListNode *)malloc(sizeof(struct ListNode));
        if (l1->val <= l2->val) {
            p->next = l1;
            l1 = l1->next;
        } else {
            p->next = l2;
            l2 = l2->next;
        }
        p = p->next;
    }
    if (l1)    p->next = l1;
    if (l2)    p->next = l2;
    return head->next;
}

struct ListNode* merge(struct ListNode** lists, int begin, int end) {
    if (end - begin == 0)    return NULL;
    if (end - begin == 1)    return *(lists + begin);

    struct ListNode* head1 = merge(lists, begin, (begin + end)/2);
    struct ListNode* head2 = merge(lists, (begin + end)/2, end);

    return mergeTwoList(head1, head2);
}

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
    return merge(lists, 0, listsSize);
}

猜你喜欢

转载自blog.csdn.net/tianxieeryang/article/details/86530782