merge k sorted lists

解法1 利用heap,手动写出

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
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
import heapq
class (object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
# 这道题主要考的是heap的运用,题目不难,但是在python heap没有一个
# 很好的实现形式,所以要在面试里熟练运用,还需要多练习
if not lists:
return None
dummy = ListNode(0)
cur = dummy
heap = []
# 1. add all list head node to the heap
for index, head in enumerate(lists):
if head:
heapq.heappush(heap, [head.val, head])
while heap:
_, node = heapq.heappop(heap)
if node.next:
heapq.heappush(heap, [node.next.val, node.next])
cur.next = node
cur = node
return dummy.next

解法2 参考了别人的答案。这个解法是divide and conquer,就是把大问题划分成小问题递归解决。这样的做法在tree的题目里很多,要仔细体会。此题加入V3

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
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
import heapq
class (object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
# 还可以用divide and conquer来实现,有点像mergesort
# 在这个mergesort的merge阶段,不是merge两个array而是merge
# 两个list
if not lists:
return None
if len(lists) == 1:
return lists[0]
mid = len(lists) / 2
left = self.mergeKLists(lists[:mid])
right = self.mergeKLists(lists[mid:])
return self.merge(left, right)
def merge(self, l1, l2):
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val > l2.val:
cur.next = l2
l2 = l2.next
else:
cur.next = l1
l1 = l1.next
cur = cur.next
if l1:
cur.next = l1
if l2:
cur.next = l2
return dummy.next