Leetcode03

笨小孩發表於2019-03-06

Merge K sorted link list

還是昨天的合併 K 個有序連結串列,今天去社群看了下,還有更簡單的解決方案,時間複雜度和空間複雜度更好,大概的思路是用python的最小堆來實現,每次從堆裡彈出最小元素,然後最近一次哪個連結串列出了最小元素就把下一個塞進堆裡,很高效,很簡潔,元祖(tuple)的運用是這個實現的點睛之筆,下面貼出程式碼

def mergeKLists(self, lists):
	from heap import heappop, heapify, heapreplace
	dummy = node = ListNode(0)
	
	# 下面這一步很贊
	h = [(n.val), n] for n in lists if n]
	
	# n 轉 minheap
	heapify(h)
	while(h):
		# 取 堆裡最小的值
		v, n = h[0]
		if n.next is None:
			heappop(h)
		else:
			# 彈出最小值,並把同一連結串列的下一個最小值放進堆中
			heapreplace(h, (n.next.val, n.next))

		node.next = n
		node = node.next

	return dummy.next
複製程式碼

Conclusion

想起了大佬 Linus 的那句話

"Bad programmers worry about the code. Good programmers worry about data structures and their relationships."