简体   繁体   English

复杂性和大O符号

[英]Complexity and Big-O Notation

What is the worst case time complexity for the following two algorithms assuming items (an ArrayList<Integer> )has enough unused space that it never needs to be re-sized? 假设项( ArrayList<Integer> )具有足够的未使用空间以至于不需要重新调整大小,以下两种算法的最坏情况时间复杂度是多少? My initial guess is that A would run slower because it has to shift every element over to add the new one at index [0] . 我最初的猜测是A会运行得更慢,因为它必须将每个元素移位以在索引[0]处添加新元素。 I think B is O(N^2) in the worst case but I am not sure. 在最坏的情况下,我认为B是O(N^2) ,但我不确定。

A. 一种。

for (int i = 0; i < N; i++)
    items.add(0, new Integer(i));

and B. 和B.

for (int i = 0; i < N; i++)
    items.add(new Integer(i));

如果你的问题是关于java的,那么第一个版本的速度较慢,并且由于你提到的原因而具有复杂度O(N^2) ,而B具有复杂度O(N)

Implementation A could be, by assuming that the items array is sufficiently large, implemented as: 通过假设items数组足够大,实现A可以实现为:

for (int i = 0; i < n; i++) {
    for (int j = items.size; j > 0; j++) {
        items[j] = items[j-1]; 
    }
    items[0] = i;
}

The total number of operations executed in this case (assuming m was the initial size of the items list) would be: 在这种情况下执行的操作总数(假设mitems列表的初始大小)将是:

This has the complexity O(n 2 ) 这具有复杂度O(n 2

Option B, on the other hand, can be implemented as 另一方面,选项B可以实现为

for (int i = 0; i < n; i++) {
    items[items.size] = i;
    items.size++;
}

and the number of operations executed in this case will be 并且在这种情况下执行的操作数量将是

This has the complexity O(n) 这具有复杂性O(n)

in A, you must shift all of the items to the right one in the internal array of the array list for each insertion. 在A中,您必须将每个插入的数组列表的内部数组中的所有项目移动到右侧。 This will be O(n^2) to complete the operation. 这将是O(n ^ 2)来完成操作。 In the second case, no shifting is needed so it will be O(n). 在第二种情况下,不需要移位,因此它将是O(n)。 In A, you are doing tons of unnecessary and expensive work. 在A中,你正在做大量不必要且昂贵的工作。

I am assuming, as you had stipulated, that the internal array is not resized. 正如您所规定的那样,我假设内部数组没有调整大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM