【问题标题】:Merging K Sorted Linked Lists, Why is Complexity O(N * K * K), not O(N * K)合并K个排序的链表,为什么复杂度是O(N * K * K),而不是O(N * K)
【发布时间】:2018-11-24 02:08:31
【问题描述】:

我有以下解决方案,但我从其他评论者那里听说它是O(N * K * K),而不是O(N * K),其中NK 列表的(最大)长度,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 循环的@987654335 @循环的主体将出现K次(listNodes.length),产生O(n * k)

为什么上面的解决方案是O(n * k * k)呢?

【问题讨论】:

  • 外循环执行N * K次,内循环执行K次
  • @PatrickRoberts 为什么外循环执行了 N * K 次?
  • 您对外部while 循环终止条件的描述不正确。实际情况是所有列表都已用尽,根据您对 N 和 K 的定义,这将是 N * K 次迭代。
  • @PatrickRoberts 我明白你现在在说什么,我只考虑用尽最长的列表而不是所有列表。谢谢。

标签: algorithm merge linked-list time-complexity big-o


【解决方案1】:

您的结果列表将最多包含 n * k 个项目。添加每个项目的成本为 O(k)(内部循环执行 k 次迭代以检查每个列表的头部)。因此总运行时间为 O(n * k * k)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多