简体   繁体   English

时间复杂度和列表中的add()

[英]Time complexity and add() in list

Here's an algorithm. 这是一个算法。 Since it's just a for loop I would see it as O(N), but I've been told it's O(N2). 由于它只是一个for循环,因此我将其视为O(N),但有人告诉我它是O(N2)。 I've been told that it's because of list.add, but that doesn't change N? 有人告诉我这是因为list.add,但这不会改变N吗? So why the change in time complexity? 那么为什么改变时间复杂度呢?

public static void mystery3(List<String> list) {
        for (int i = 0; i < list.size() - 1; i += 2) {
            String first = list.remove(i);
            list.add(i + 1, first);
        }
    }

If you are using an array (Arraylist), remove(i) takes O(n) and the add(...) takes O(n). 如果使用数组(Arraylist),则remove(i)取O(n),而add(...)取O(n)。 That's because finding element at index i takes O(1) but resizing takes O(n). 这是因为在索引i处查找元素需要O(1),但调整大小需要O(n)。

If you use an linked list, remove(i) takes O(n) and `add(...) takes O(n). 如果使用链表,则remove(i)取O(n),而`add(...)取O(n)。 That's because finding element at index i takes O(n) and removing takes O(1). 这是因为在索引i处查找元素需要O(n),而删除要花费O(1)。

Since you a calling the methods n/2 times, its whole runtime is O(n^2). 由于您调用方法的次数为n / 2次,因此其整个运行时间为O(n ^ 2)。

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

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