0
点赞
收藏
分享

微信扫一扫

leetcode-23-Merge k Sorted Lists

晗韩不普通 2023-08-23 阅读 43


First, we can use priority_queue to deal with that, the time complexity is O(Nlog^k). Since priority_queue is basically a heap, every time we only need to compare the value in O(logk) time, instead of O(n) time. So we need to compare O(Nlog^k) in total.

Second is use divide and conquer. it is similar to merge sort. But the space complexity seems exceeded.

Pattern of mergesort:

merge(l1, l2):
	cur = -1;
	whlie(l1 && l2){
		if(l1->v < l2->v)
			cur->next = l1
			l1 = l1->next
		else
			cur->next = l2
			l2 = l2->next

		cur = cur->next
	}

	if(l1)
		cur->next = l1
	if(l2)
		cur->next = l2;

	return root.next;
	
divide(s, l, r):
	if(l == r)
		return s[l]
	merged = null
	if(l < r)
		mid = (l + r) / 2;
		l1 = divide(s, l, mid)
		l2 = divide(s, mid + 1, r)
		merged = merge(l1, l2)
	return merged


举报

相关推荐

0 条评论