LintCode Q104 Merge k Sorted Lists in Python

  • Jinhai ZHOU
  • 5 Minutes
  • 2016年11月5日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def mergeKLists(self, lists):
# write your code here
if len(lists) == 0:
return None
elif len(lists) == 1:
return lists[0]
elif len(lists) == 2:
node_1 = lists[0]
node_2 = lists[1]
node = ListNode(None)
head = node
while(node_1 is not None and node_2 is not None):
if node_1.val <= node_2.val:
node.next = ListNode(node_1.val)
node_1 = node_1.next
else:
node.next = ListNode(node_2.val)
node_2 = node_2.next
node = node.next
if node_1 is None:
node.next = node_2
elif node_2 is None:
node.next = node_1
return head.next
else: # len > 2
node_1 = self.mergeKLists(lists[:len(lists)/2])
node_2 = self.mergeKLists(lists[len(lists)/2:])
return self.mergeKLists([node_1, node_2])
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。