[英]Merging K Sorted Linked Lists, Why is Complexity O(N * K * K), not O(N * K)
我有以下解決方案,但我從其他審閱者那里聽到,它是O(N * K * K)
,而不是O(N * K)
,其中N
是K
列表的(最大)長度, K
是數字列表。 例如,給定列表[1, 2, 3]
和[4, 5]
, N
為3, K
為2。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private void advance(final ListNode[] listNodes, final int index) {
listNodes[index] = listNodes[index].next;
}
public ListNode mergeKLists(final ListNode[] listNodes) {
ListNode sortedListHead = null;
ListNode sortedListNode = null;
int associatedIndex;
do {
int minValue = Integer.MAX_VALUE;
associatedIndex = -1;
for (int listIndex = 0; listIndex < listNodes.length; listIndex++) {
final ListNode listNode = listNodes[listIndex];
if (listNode != null && listNode.val < minValue) {
minValue = listNode.val;
associatedIndex = listIndex;
}
}
if (associatedIndex != -1) {
if (sortedListNode == null) {
sortedListNode = new ListNode(minValue);
sortedListHead = sortedListNode;
}
else {
sortedListNode.next = new ListNode(minValue);
sortedListNode = sortedListNode.next;
}
advance(listNodes, associatedIndex);
}
}
while (associatedIndex != -1);
return sortedListHead;
}
}
我的理由是, do-while
循環的主體將發生N
次(因為最長的列表被迭代通過時, do-while
循環的停止條件已滿足),而do-while
循環的for
循環的主體將發生K
次。 ( listNodes.length
), listNodes.length
O(n * k)
。
為什么上述解決方案為O(n * k * k)
?
您的結果列表最多包含n * k個項目。 將這些項目的每一個相加會花費O( k )(內部循環執行k次迭代以檢查每個列表的頭部)。 因此,總運行時間為O( n * k * k )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.