What is the cost/ complexity of insert in list at some location?

后端 未结 4 1090
慢半拍i
慢半拍i 2020-12-05 05:06

In Python, a list has list.insert(i, x) to \"Insert an item at a given position.\". In C++, there is a list as well. In C++, cost/complexity of inserting an el

4条回答
  •  醉酒成梦
    2020-12-05 05:43

    list

    The Average Case assumes parameters generated uniformly at random.

    Internally, a list is represented as an array; the largest costs come from growing beyond the current allocation size (because everything must move), or from inserting or deleting somewhere near the beginning (because everything after that must move). If you need to add/remove at both ends, consider using a collections.deque instead.

    enter image description here

    So inserting an element at given position will always have the time complexity of O(n) as both insert method and slicing has time complexity of O(n) and O(k). Only append which inserts at the end of list have O(1) time complexity. From Python Wiki

    Lists:
                                   Complexity
    Operation     | Example      | Class         | Notes
    --------------+--------------+---------------+-------------------------------
    Index         | l[i]         | O(1)          |
    Store         | l[i] = 0     | O(1)          |
    Length        | len(l)       | O(1)          |
    Append        | l.append(5)  | O(1)          |
    Clear         | l.clear()    | O(1)          | similar to l = []
    
    Slice         | l[a:b]       | O(b-a)        | l[1:5]:O(l)/l[:]:O(len(l)-0)=O(N)
    Extend        | l.extend(...)| O(len(...))   | depends only on len of extension
    Construction  | list(...)    | len(...)      | depends on lenghth of argument
    
    check ==, !=  | l1 == l2     | O(N)          |
    Insert        | l[a:b] = ... | O(N)          |
    Delete        | del l[i]     | O(N)          | 
    Remove        | l.remove(...)| O(N)          | 
    Containment   | x in/not in l| O(N)          | searches list
    Copy          | l.copy()     | O(N)          | Same as l[:] which is O(N)
    Pop           | l.pop(...)   | O(N)          |
    Pop           | l.pop()      | O(1)          | same as l.pop(-1), popping at end
    Extreme value | min(l)/max(l)| O(N)          |
    Reverse       | l.reverse()  | O(N)          |
    Iteration     | for v in l:  | O(N)          |
    
    Sort          | l.sort()     | O(N Log N)    | key/reverse doesn't change this
    Multiply      | k*l          | O(k N)        | 5*l is O(N): len(l)*l is O(N**2)
    

    From here

提交回复
热议问题