Leetcode题库——23.合并k个排序链表
2024-10-16 07:44:32
@author: ZZQ
@software: PyCharm
@file: mergeKLists.py
@time: 2018/10/12 19:55
说明:合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例 :
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
思路:两两合并再合并,判断奇偶,每次用一个新的数组来存放当前经过合并后的新的链表首节点,时间复杂度:O(nlogn)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None and l2 is None:
return None
if l1 is None:
return l2
if l2 is None:
return l1
l3 = ListNode(0)
head = l3
while l1 is not None and l2 is not None:
if l1.val > l2.val:
l3.next = l2
l2 = l2.next
else:
l3.next = l1
l1 = l1.next
l3 = l3.next
if l1 is not None and l2 is None:
l3.next = l1
if l1 is None and l2 is not None:
l3.next = l2
return head.next
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0:
return None
cur_list = lists
while len(cur_list) > 1:
cur_temp_list = []
if len(cur_list) % 2:
for i in range((len(cur_list) - 1) / 2):
cur_temp_list.append(self.mergeTwoLists(cur_list[i * 2], cur_list[i * 2 + 1]))
cur_temp_list.append(cur_list[len(cur_list)-1])
else:
for i in range(len(cur_list) / 2):
cur_temp_list.append(self.mergeTwoLists(cur_list[i * 2], cur_list[i * 2 + 1]))
cur_list = cur_temp_list
return cur_list[0]
最新文章
- Ubuntu Server 14.04 --secure-file-priv error in MySql 解决方案
- ASP.NET杂谈-一切都从web.config说起(2)(ConfigSections详解-下)
- CAS单点登录配置
- 通过Greasemonkey实现网页图片自动点击
- MySQL如何查询两个日期之间的记录
- 如何为Linux生成和打上patch
- 一点关于Ajax和一个等待图标的显示
- nginx安装lua-nginx-module模块
- 製程能力介紹(SPC introduction) ─ Cpk之製程能力解釋
- VS2015企业版本(安装包+key)
- 在asp.net webservice中如何使用session
- UVALive 7045 Last Defence
- win10环境下利用pyinstaller把python代码(.py)打包成可执行文件(.exe)
- Java课后练习
- [NOI 2011]阿狸的打字机
- 1.用代码演示String类中的以下方法的用法 (2018.08.09作业)
- linux内存源码分析 - SLUB分配器概述
- selenium 淘宝登入反爬虫解决方案(亲测有效)
- python的优点
- java学习笔记37(sql工具类:JDBCUtils)
热门文章
- 什么是websoket
- 20155307《网络对抗》PC平台逆向破解(二)
- elastic-job+zookeeper实现分布式定时任务调度的使用(springboot版本)
- Keil 中的Code,RO-data,RW-data,ZI-data
- 2734: [HNOI2012]集合选数
- 4557: [JLoi2016]侦察守卫
- codeforces 914 D 线段树+数学
- 动态权限<;二>;之淘宝、京东、网易新闻 权限申请交互设计对比分析
- CentOS安装GoAccess
- centos7上的postgresql10安装和配置