๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/์•Œ๊ณ ๋ฆฌ์ฆ˜

[Algorithm] ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜ (Two Pointers)

1. ํˆฌ ํฌ์ธํ„ฐ(Two Pointers) ์•Œ๊ณ ๋ฆฌ์ฆ˜

  • ๋ฐฐ์—ด์˜ ํŠน์ • ์—ฐ์†๋œ ๊ตฌ๊ฐ„์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒฝ์šฐ ์‚ฌ์šฉ
  • ๋ฆฌ์ŠคํŠธ์— ์ˆœ์ฐจ์ ์œผ๋กœ ์ ‘๊ทผํ•ด์•ผ ํ•  ๋•Œ, ๋‘๊ฐœ์˜ ์ ์„ ์ด์šฉํ•ด ์œ„์น˜๋ฅผ ๊ธฐ๋กํ•˜๋ฉด์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ธฐ๋ฒ•
  • $O(N)$

2. ์˜ˆ์‹œ ๋ฌธ์ œ

  • [1,2,3,2,5]
  • ํ•ฉ์ด 5 ์ธ ๋ถ€๋ถ„ ์—ฐ์† ์ˆ˜์—ด์˜ ๊ฐœ์ˆ˜ ๊ตฌํ•˜์‹œ์˜ค
    • ๊ฐ ์ง€์ ์—์„œ ๊ตฌ๊ฐ„์„ ๋Š˜๋ ค๊ฐ€๋ฉฐ ์—ฐ์†๋˜๋Š” ์ˆ˜๋ฅผ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•?
      • ์‹œ๊ฐ„ ๋ณต์žก๋„ : $O(n^2)$
      • ๋ฐ์ดํ„ฐ์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋งŽ์•„์ง€๋ฉด ์‹œ๊ฐ„์ด ๋งŽ์ด ๊ฑธ๋ฆผ
    • $O(N)$์œผ๋กœ ํ’€๋ ค๋ฉด?
      • ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์‚ฌ์šฉํ•˜๊ธฐ

3. ํ’€์ด

  • start, end ํฌ์ธํ„ฐ๋ฅผ ์ฒซ ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก!
  • ํ•ฉ์ด 5๋ณด๋‹ค ์ž‘์œผ๋ฉด end ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™ (ํ•ฉ์„ ๋Š˜๋ฆผ)
  • ํ•ฉ์ด 5๋ณด๋‹ค ํฌ๋ฉด start๋ฅผ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™ (ํ•ฉ์„ ์ค„์ž„)
  • ํ•ฉ์ด 5๊ฐ€๋˜๋ฉด count, start๋ฅผ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™
#๋ฐ์ดํ„ฐ์˜ ๊ฐœ์ˆ˜ N๊ณผ ๋ถ€๋ถ„ ์—ฐ์† ์ˆ˜์—ด์˜ ํ•ฉ M์„ ์ž…๋ ฅ ๋ฐ›๊ธฐ
n, m = 5,5
data = [1,2,3,2,5]

result = 0
summary = 0
end = 0

#start๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ์ฆ๊ฐ€์‹œํ‚ค๋ฉฐ ๋ฐ˜๋ณต
for start in range(n):
    #end๋ฅผ ๊ฐ€๋Šฅํ•œ ๋งŒํผ ์ด๋™์‹œํ‚ค๊ธฐ
    while summary < m and end <n:
        summary += data[end]
        end +=1
    #๋ถ€๋ถ„ ํ•ฉ์ด m์ผ ๋•Œ ์นด์šดํŠธ ์ฆ๊ฐ€
    if summary == m:
        result+=1
    summary -=data[start]

print(result)

4. ์ฐธ๊ณ 

https://www.youtube.com/watch?v=rI8NRQsAS_s