Leetcode 23. Merge k Sorted Lists(python)
2016-04-07 17:44
741 查看
分治法两两合并,才没有超时
# 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 """ if len(lists)==0: return [] return self.merge(lists,0,len(lists)-1) def merge(self,lists,l,r): if l<r: mid=(l+r)/2 return self.mergeTwoLists(self.merge(lists,l,mid),self.merge(lists,mid+1,r)) return lists[l] def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ res=cur=ListNode(0) while l1 and 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 or l2 return res.next
相关文章推荐
- A Byte of Python 笔记(12)python 标准库:sys、os,更多内容
- Python ctypes 模块
- python学习笔记--socket
- Ubuntu 下Python 环境问题
- python学习4
- python+opencv鼠标操作以及制作调色板并画图
- leetcode [python] 【144】 Binary Tree Preorder Traversal
- 大顶堆进行升序排序的python实现
- 初学python(对比java语言不同) 第四篇
- leetcode [python] 【338】Counting Bits
- [LeetCode]题解(python):139-Word Break
- python爬虫系列文章
- A Byte of Python 笔记(11)异常:try..except、try..finally
- python 学习笔记1(序列;if/for/while;函数;类)
- [LeetCode]题解(python):138-Copy List with Random Pointer
- [LeetCode]题解(python):137-Single Number II
- Sublime Text 3 配置python开发环境遇见的问题
- Win7下Python2.7环境安装paramiko模块
- python 列表、元组、字典
- 初学python(对比java语言不同) 第三篇