๐
ํ์ด์ฌ ์๊ณ ๋ฆฌ์ฆ ์ธํฐ๋ทฐ
์ฑ ์ ์ฐธ๊ณ ํ์ต๋๋ค.
์ ์ ์ซ์ ๋ฐฐ์ด์ด ์ฃผ์ด์ง๊ณ ๋ฐฐ์ด์ ๋งจ ์ผ์ชฝ์์ ๋งจ ์ค๋ฅธ์ชฝ์ผ๋ก ์ด๋ํ๋ k ํฌ๊ธฐ์ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๊ฐ ์์ต๋๋ค. ์ฌ๋ผ์ด๋ฉ ์๋์ฐ์์ k ๊ฐ์ ์ซ์ ๋ง ๋ณผ ์ ์์ต๋๋ค. ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๊ฐ ํ ์์น ์ค๋ฅธ์ชฝ์ผ๋ก ์ด๋ํ ๋๋ง๋ค ์ต๋ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๋ฅผ ๊ฐ์ ๋ฃ์ ๊ฐ๋ค์ ๋ฐํํ์ธ์.
๋จผ์ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๋ก ์ฌ์ฉํ ํ๋ฅผ ์ ์ธํ๋ค.
๋ฐฐ์ด์ ๋๋ฉด์ ๋ชจ๋ ์ธ๋ฑ์ค์ ๋ํด ๋ฐ๋ณต์ ์์ํ๋ค.
1. ํ์ฌ์ธ๋ฑ์ค์ ์ซ์๋ณด๋ค ์์ ์ซ์๋ฅผ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ์์ ๋ชจ๋ ๋นผ๋ธ๋ค.
2. ํ์ฌ์ธ๋ฑ์ค๋ฅผ ์ฌ๋ผ์ด๋ฉ์๋์ฐ(ํ)์ ์ฝ์
ํ๋ค.
3. ๋ง์ฝ, ๊ฐ์ฅ ์ค๋๋ ์ธ๋ฑ์ค์ ํ์ฌ ์ธ๋ฑ์ค์ ์ฐจ์ด๊ฐ k๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๋ค๋ฉด ์ค๋๋ ์ธ๋ฑ์ค๋ฅผ ์ ๊ฑฐํ๋ค.
๋ง์ง๋ง์ ์๋ i + 1 >= k๋ ์ฒ์ ์์ ์ k๊ฐ ์ด์์ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ๋ฃ์ด๋ณด๊ณ ์์ํ๊ธฐ ์ํจ์ด๋ค.
4. ์ฌ๋ผ์ด๋ฉ ์๋์ฐ์ ๊ฐ์ฅ ๋ง์ง๋ง ์ธ๋ฑ์ค๊ฐ ํญ์ ํ์ฌ ์๋์ฐ์์ ๊ฐ์ฅ ํฐ ๊ฐ์ ๊ฐ๊ฒ ๋๋ฏ๋ก ๊ฒฐ๊ณผ์ ์ฝ์
ํ๋ค.
# leet code solution (Very GOOD)
from collections import deque
class Solution:
def maxSlidingWindow(self, nums, k):
res = []
bigger = deque()
for i, n in enumerate(nums):
# make sure the rightmost one is the smallest
while bigger and nums[bigger[-1]] <= n:
bigger.pop()
# add in
bigger += [i]
# make sure the leftmost one is in-bound
if i - bigger[0] >= k:
bigger.popleft()
# if i + 1 < k, then we are initializing the bigger array
if i + 1 >= k:
res.append(nums[bigger[0]])
return res
# book solution ์๊ฐ์ด๊ณผ
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
results = []
window = collections.deque()
current_max = float('-inf')
for i, v in enumerate(nums):
window.append(v)
if i < k - 1:
continue
# ์๋ก ์ถ๊ฐ๋ ๊ฐ์ด ๊ธฐ์กด ์ต๋๊ฐ๋ณด๋ค ํฐ ๊ฒฝ์ฐ ๊ต์ฒด
if current_max == float('-inf'):
current_max = max(window)
elif v > current_max:
current_max = v
results.append(current_max)
# ์ต๋๊ฐ์ด ์๋์ฐ์์ ๋น ์ง๋ฉด ์ด๊ธฐํ
if current_max == window.popleft():
current_max = float('-inf')
return results