Big O (3)

์ฑ„์˜๋ฏผยท2024๋…„ 3์›” 19์ผ
0
post-custom-banner

๐Ÿ“š Different Terms for Inputs

def print_items(a, b) :
	for i in range(a):
    	print(i)
	for j in range(b):
    	print(j)
  • ์ด์ „์— ๋ดค๋˜ O(2n)์— ๊ฒฝ์šฐ์™€๋Š” ๋‹ค๋ฅด๊ฒŒ, ์œ„์— ํ•จ์ˆ˜๋Š” ๋‘ ๊ฐœ์˜ ํŒŒ๋ผ๋ฉ”ํ„ฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ์œ„์™€ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” O(a + b)๋กœ ์ตœ๋Œ€ํ•œ ๋‹จ์ˆœํ™” ํ•  ์ˆ˜ ์žˆ๋‹ค.
def print_items(a, b) :
	for i in range(a):
		for j in range(b):
    		print(i, j)
  • ์œ„ ๊ฐ™์€ ๊ฒฝ์šฐ๋„, ์„œ๋กœ ๋‹ค๋ฅธ ํŒŒ๋ผ๋ฉ”ํ„ฐ๊ฐ€ ๋‘ ๊ฐœ ์ฃผ์–ด์กŒ๊ธฐ์—, O(n^2)๋กœ ํ‘œ์‹œํ•˜๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ O(a * b)๋กœ ๋‹จ์ˆœํ™” ํ•ด์•ผ ํ•œ๋‹ค.

๐Ÿ“š Big O of Lists

๐Ÿ’ก (๋ฆฌ์ŠคํŠธ) ์ถ”๊ฐ€, ์ œ๊ฑฐ์‹œ์— Big O

  • my_list = [11, 3, 23, 7]
      1. my_list.append(15) -> 4๋ฒˆ ์ธ๋ฑ์Šค์— 15๊ฐ€ ์ถ”๊ฐ€๋จ. ์ฆ‰ O(1)
      1. my_list.pop() -> 4๋ฒˆ ์ธ๋ฑ์Šค์˜€๋˜ 15๊ฐ€ ์ œ๊ฑฐ๋จ. ์ฆ‰ O(1)
      1. my_list.pop(0) -> 0๋ฒˆ ์ธ๋ฑ์Šค์ธ 11์ด ์ œ๊ฑฐ๋จ, ๊ทธ๋Ÿฌ๋‚˜ ์ด ๊ฒฝ์šฐ ํ•ด๋ฐฉ ๋ฐฐ์—ด์—๋Š” 0๋ฒˆ ์ธ๋ฑ์Šค๊ฐ€ ๋น„์–ด์žˆ๊ธฐ์— ๋‚˜๋จธ์ง€ ์ธ๋ฑ์Šค๋“ค์„ ๋‹ค์‹œ ์ธ๋ฑ์‹ฑํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. ์ฆ‰ O(n)
      1. my_list.insert(0, 11) -> 0๋ฒˆ ์ธ๋ฑ์Šค์— 11์ด ์ถ”๊ฐ€๋จ, ๊ทธ๋Ÿฌ๋‚˜ ์ด ๊ฒฝ์šฐ ์ด๋ฏธ 0๋ฒˆ ์ธ๋ฑ์Šค์— ๋‹ค๋ฅธ ๊ฐ’์ด ์žˆ๊ธฐ์— ์ธ๋ฑ์Šค๋“ค์„ ๋‹ค์‹œ ์ธ๋ฑ์‹ฑํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. ์ฆ‰ O(n)
      1. my_list.insert(1, 'hi') -> 1๋ฒˆ ์ธ๋ฑ์Šค์— 'hi'๊ฐ€ ์ถ”๊ฐ€๋˜๊ณ , ๋‚˜๋จธ์ง€ ์ธ๋ฑ์Šค๋“ค์„ ๋‹ค์‹œ ์ธ๋ฑ์‹ฑํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. ์ฆ‰ O(n)

๐Ÿ’ก (๋ฆฌ์ŠคํŠธ) ๋ฆฌ์ŠคํŠธ ๋‚ด ํ•ญ๋ชฉ์„ ๊ฐ’์œผ๋กœ ํƒ์ƒ‰์‹œ์— Big O

  • my_list = [11, 3, 23, 7]
    • ๋ฐฐ์—ด์„ iterateํ•ด์„œ ๊ฐ’์„ ์ฐพ์„ ๊ฒฝ์šฐ, ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋งŒํผ ๋Œ์•„์•ผ ํ•œ๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ O(n)
    • ์ธ๋ฑ์Šค๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ฐ’์„ ์ฐพ์„ ๊ฒฝ์šฐ๋Š” ๋ฉ”๋ชจ๋ฆฌ๋กœ ๋ฐ”๋กœ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ, O(1)
  • ๐Ÿ—ฃ๏ธ (์ฐธ๊ณ ) n์€ ๋ฐฐ์—ด์— ์žˆ๋Š” ์›์†Œ์— ๊ฐฏ์ˆ˜

๐Ÿ“š Big O < wrap up >

๐Ÿ’ก n = 100 ์ผ๋•Œ ๊ฐ Big O ์š”์†Œ๋ณ„ ์†Œ์š” ์‹œ๊ฐ„

  • O(1) = 1
  • O(log n) = approx 7
  • O(n) = 100
  • O(n^2) = 10,000

๐Ÿ’ก n = 1,000 ์ผ๋•Œ ๊ฐ Big O ์š”์†Œ๋ณ„ ์†Œ์š” ์‹œ๊ฐ„

  • O(1) = 1
  • O(log n) = approx 10
  • O(n) = 1,000
  • O(n^2) = 1,000,000

๐Ÿ’ก Big O ์š”์†Œ๋ณ„ ์šฉ์–ด ์ •๋ฆฌ

  • O(1) = constant
  • O(log n) = divide and conquer
  • O(n) = proportional
  • O(n^2) = loop within a loop

๐Ÿ—ฃ๏ธ Big O, ์‹œ๊ฐ„/๊ณต๊ฐ„ ๋ณต์žก๋„, ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ๋Œ€ํ•ด ์ •๋ฆฌ๊ฐ€ ์ž˜ ๋˜์–ด ์žˆ๋Š” ์›น์‚ฌ์ดํŠธ
https://www.bigocheatsheet.com/

profile
์‹œ๊ฐ์ ์ธ ์ฝ”๋”ฉ์„ ์ฆ๊ธฐ๋Š” ๊ฐœ๋ฐœ์ž ์ง€๋ง์ƒ ์ฑ„์˜๋ฏผ ์ž…๋‹ˆ๋‹ค;
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€