LeetCode: 合并K个排序链表 python实现

1. 题目描述

        合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

2. 代码实现

方法1:逐一两两合并链表:

        执行用时 :5792 ms, 在所有 Python 提交中击败了5.03%的用户
        内存消耗 :18.4 MB, 在所有 Python 提交中击败了56.25%的用户

# 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 lists: List[ListNode]
        :rtype: ListNode
        """
        lens = len(lists)
        if lens==0:
            return lists
        else:
	        while lens>=2:
	           # 将前两个链表和并后赋值给原lists[1]位置
	            lists[1] =  self.merge2List(lists[0], lists[1])
	            # 去除原lists第一个链表后为新的lists
	            lists = lists[1:]
	            lens -= 1
	        return lists[0]
    # 合并两个链表的函数
    def merge2List(self, list1, list2):
        LiNo = ListNode(-1)
        current = LiNo
        while list1 and list2:
            if list1.val>=list2.val:
                current.next = list2
                current = current.next
                list2 = list2.next
            else:
                current.next = list1
                current = current.next
                list1 = list1.next
        if list1:
            current.next = list1
        else:
            current.next = list2
        return LiNo.next

复杂度分析:

        时间复杂度: O(kN),其中k 是链表的数目。
我们可以在 O(n) 的时间内合并两个有序链表,其中 n 是两个链表的总长度。
        空间复杂度:O(1)。
我们可以在 O(1)空间内合并两个有序链表。

方法2:暴力法

        遍历所有链表,将所有节点的值放到一个数组中。将这个数组排序,然后遍历所有元素得到正确顺序的值。用遍历得到的值,创建一个新的有序链表。

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        self.nodes = []
        head = point = ListNode(0)
        # 获得所有节点的值
        for l in lists:
            while l:
                self.nodes.append(l.val)
                l = l.next
        #   sorted()返回升序
        for x in sorted(self.nodes):
            point.next = ListNode(x)
            point = point.next
        return head.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狂奔的菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值