[Lintcode]128. Longest Consecutive Sequence/[Leetcode]23. Merge k Sorted Lists

128. Longest Consecutive Sequence / 23. Merge k Sorted Lists

  • 本题难度: Hard/Medium
  • Topic: Data Structure

Description

Merge k sorted linked lists and return it as one sorted list.

Analyze and describe its complexity.

Example
Example 1:
Input: [2->4->null,null,-1->null]
Output: -1->2->4->null

Example 2:
Input: [2->6->null,5->null,7->null]
Output: 2->5->6->7->null

我的代码

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param l1: ListNode l1 is the head of the linked list
    @param l2: ListNode l2 is the head of the linked list
    @return: ListNode head of linked list
    """
    def mergeKLists(self, lists):
        # write your code here
        l = len(lists)
        if l == 0:
            return None
        left = 0
        right = l-1
        return self.merge(left,right,lists)


    def merge(self,left,right,lists):
        if left == right:
            return lists[left]
        if left == right-1:
            return self.mergeTwoLists(lists[left],lists[right])
        mid = left+(right-left)//2
        return self.mergeTwoLists(self.merge(left,mid,lists),self.merge(mid+1,right,lists))

    def mergeTwoLists(self, l1, l2):
        # write your code here
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        res = pos = ListNode(0)
        while (l1 and l2):
            if l1.val < l2.val:
                pos.next = l1
                l1 = l1.next
            else:
                pos.next = l2
                l2 = l2.next
            pos = pos.next
        if l1:
            pos.next = l1
        else:
            pos.next = l2
        return res.next

别人的代码

思路
merge
二分法
将两个有序数列merge可参照165. Merge Two Sorted Lists/21. Merge Two Sorted Lists

  • 时间复杂度 O(log(n))

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10391310.html