您的位置:首页 > 编程语言 > Python开发

24 leetcode - Merge k Sorted Lists

2016-11-23 14:19 363 查看
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
中文:合并k个有序链表
'''
# 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
"""
#将空的去掉
index = 0
for val in lists:
if val:
lists[index] = val
index += 1
lists = lists[:index]
if not lists:
return []
#将所有节点遍历一次,存入字典中
d = {}
for i in range(len(lists)):
node = lists[i]
while node != None:
if d.has_key(node.val):
d[node.val].append(node)
else:
d[node.val] = [node]
node = node.next
#将键值排序,从小到大从字典中取值
l = d.keys()
l.sort()
start = node = d[l[0]].pop(0)
for i in l:
for j in d[i]:
start.next = j
start = start.next
start.next = None
return node

if __name__ == "__main__":
s = Solution()
s.mergeKLists([[],[]])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息