Leetcode03

Merge K sorted link list

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

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 的那句話python

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

相關文章
相關標籤/搜索