Python - List,Dict,Set의 시간복잡도 Big-O

최준근·2021년 9월 14일
0

알고리즘을 풀면서 문제를 맞추어도 효율이 안좋은 경우가 종종 있다. 시간복잡도를 최대한 줄여 효율을 끌어올려야 겠다고 생각이 들어 시간복잡도를 정리해본다.

삽입(insert,pop), 제거(delete, remove) , 탐색(check ==,≠) 포함여부 확인( catainment(in, not in))의 경우 List는 전부 O(N)이다. Set,Dict은 O(1)혹은 O(len)의 시간을 가지고 있다.

이걸보면 삽입,삭제, 탐색, 포함여부 확인등의 문제는 list보다 set,dict을 사용하는게 효율면에서 뛰어나다고 생각한다.

List

OperationExampleBig-ONotes
Indexl[i]O(1)
Storel[i] = 0c2r2
Lengthlen(l)c3r3
Appendl.append(5)O(1)mostly: ICS-46 covers details
Popl.pop()O(1)same as l.pop(-1), popping at end
Clearl.clear()O(1)similar to l = []
Slicel[a:b]O(b-a)l[1:5]:O(l)/l[:]:O(len(l)-0)=O(N)
Extendl.extend(…)O(len(…))depends only on len of extension
Constructionlist(…)O(len(…))depends on length of … iterable
check ==, !=l1 == l2O(N)
Insertl[a:b] = …O(N)
Delete dell[i]O(N)depends on i; O(N) in worst case
Containmentx in/not in lO(N)linearly searches list
Copyl.copy()O(N)Same as l[:] which is O(N)
Removel.remove(…)O(N)
Popl.pop(i)O(N)O(N-i): l.pop(0):O(N) (see above)
Extreme valuemin(l)/max(l)O(N)linearly searches list for value
Reversel.reverse()O(N)
Iterationfor v in l:O(N)Worst: no return/break in loop
Sortl.sort()O(N Log N)key/reverse mostly doesn’t change
Multiplyk*lO(k N)5l is O(N): len(l)l is O(N**2)

Set

OperationExampleBig-ONotes
Lengthlen(s)O(1)
Adds.add(5)O(1)
Containmentx in/not in sO(1)compare to list/tuple - O(N)
Removes.remove(..)O(1)compare to list/tuple - O(N)
Discards.discard(..)O(1)
Pops.pop()O(1)popped value “randomly” selected
Clears.clear()O(1)similar to s = set()
Constructionset(…)O(len(…))depends on length of … iterable
check ==, !=s != tO(len(s))same as len(t); False in O(1) if the lengths are different
\<=/<s <= tO(len(s))issubset
/>=/>s >= tO(len(t))issuperset s <= t == t >= s
Unions tO(len(s)+len(t))
Intersections & tO(len(s)+len(t))
Differences - tO(len(s)+len(t))
Symmetric Diffs ^ tO(len(s)+len(t))
Iterationfor v in s:O(N)Worst: no return/break in loop
Copys.copy()O(N)

Dict

OperationExampleBig-ONotes
Indexd[k]O(1)
Stored[k] = vO(1)
Lengthlen(d)O(1)
Deletedel d[k]O(1)
get/setdefaultd.get(k)O(1)
Popd.pop(k)O(1)
Pop itemd.popitem()O(1)popped item “randomly” selected
Cleard.clear()O(1)similar to s = {} or = dict()
Viewd.keys()O(1)same for d.values()
Constructiondict(…)O(len(…))depends # (key,value) 2-tuples
Iterationfor k in d:O(N)all forms: keys, values, items
profile
느려도 좋으니 꾸준하게

0개의 댓글