239. Sliding Window Maximum
1. Description
-
You are given an array of integersย
nums, there is a sliding window of sizeยkย which is moving from the very left of the array to the very right. You can only see theยkย numbers in the window. Each time the sliding window moves right by one position. -
Returnย the max sliding window.
2. Example
Example 1
Input: nums =
[1,3,-1,-3,5,3,6,7], k = 3 Output:[3,3,5,5,6,7]Explanation: Window position Max
โ
[1 3 -1]-3 5 3 6 7โ 3 โ1[3 -1 -3]5 3 6 7โ 3 โ1 3[-1 -3 5]3 6 7โ 5 โ1 3 -1[-3 5 3]6 7โ 5 โ1 3 -1 -3[5 3 6]7โ 6 โ1 3 -1 -3 5[3 6 7]โ 7
Example 2
Input: nums =
[1], k = 1 Output:[1]
3. Solution
- Runtime: 179
- Time Complexity:
O(N) - ์ค๋ช
deque๋ฅผ ๋ง๋ ๋ค.- ๐
deque๋ฅผ ์ฌ์ฉํ์ฌ ๋ถํ์ํ ์์๋ค์ ์ ๊ฑฐํ๊ณ ์ ํจํ ์ต๋๊ฐ๋ง ๋จ๊ฒจ ์๊ฐ ๋ณต์ก๋๋ฅผ ์ค์ธ๋ค. - ๐
deque์ ์ธ๋ฑ์ค๋ฅผ ์ ์ฅํ ์ด์window๋ฒ์ ๊ด๋ฆฌ๋ฅผ ํ๊ธฐ ์ํจ์ด๋ค.nums[q[0]](์๋์ฐ์์ ๊ฐ์ฅ ํฐ ๊ฐ์ ์ธ๋ฑ์ค๋ฅผ ์๋ฏธ)์ ํตํด ์ต๋๊ฐ์ ๋น ๋ฅด๊ฒ ๊ฐ์ ธ์ค๊ธฐ ์ํจ์ด๋ค.
- ๐
r์ดlen(nums)๊น์ง ๋๋ฌํ ๋๊น์ง ๋ฐ๋ณต๋ฌธ์ ์คํํ๋ค.- ํ์ฌ ์์๋ณด๋ค ์์ ๊ฐ๋ค์ ๋ฑ์์ ์ ๊ฑฐํ๋ค.
q๊ฐ ๋น์ด์์ง ์๊ณnums[q[-1]] < nums[r]์ผ ๋q[-1]์ ํ์ฌ ๋ฑ์์ ๊ฐ์ฅ ์ต๊ทผ์ ์ถ๊ฐ๋ ์ธ๋ฑ์ค์ด๋ค.- ๋ง์ฝ ํ์ฌ ์ซ์(
nums[r])๊ฐ ๋ฑ์ ๋ง์ง๋ง ์ซ์(nums[q[-1]])๋ณด๋ค ํฌ๋ค๋ฉด- ๋ฑ์ ๋ง์ง๋ง ์์๋ฅผ ์ ๊ฑฐํ๋ค.
deque์ ์ฒซ ๋ฒ์งธ ๊ฐ์ด ์๋์ฐ ๋ฒ์๋ฅผ ๋ฒ์ด๋๋ฉด ์ ๊ฑฐํ๋ค.q[0]์ ํ์ฌ ๋ฑ์์ ๊ฐ์ฅ ํฐ ๊ฐ์ ๊ฐ์ง ์ธ๋ฑ์ค์ด๋ค.q[0]์ด ํ์ฌ ์๋์ฐ ๋ฒ์( l ~ r ) ๋ฐ์ ์๋ค๋ฉด ์ ๊ฑฐ
- ์๋์ฐ ํฌ๊ธฐ๊ฐ
k์ด์์ด๋ฉด ์ต๋๊ฐ ์ ์ฅ(r + 1) >= k: ์๋์ฐ ํฌ๊ธฐ ์ฆ r์ด k์ ๋๋ฌํ์ ๋,nums[q[0]]์result์ ์ถ๊ฐํ๋ค.- ๐
q[0]์ ํ์ฌ ์๋์ฐ์์ ์ต๋๊ฐ์ ์ธ๋ฑ์ค์ด๋ฏ๋กnums[q[0]]์ด ์ต๋๊ฐ. - ๐
l์ ์ฆ๊ฐ์ํค๋ ์ด์l์ ์๋์ฐ ํฌ๊ธฐk๊ฐ ์ ์ง๋ ์ดํ์๋ง ์ฆ๊ฐ์์ผ์ผ ํ๋ค.r์ด ์ฆ๊ฐํ๋ฉด์ ์๋์ฐ ํฌ๊ธฐ๋ฅผ ์ฆ๊ฐ์ํค๊ณk์ ๋๋ฌํ๋ฉดl์ ์ฆ๊ฐ์ํค๊ณ ๊ทธ๋ค์r์ ์ฆ๊ฐ์ํค๋ ๊ตฌ์กฐ์ด๋ค.
r๋ฅผ ์ฆ๊ฐ์์ผr์ดk์ ๋๋ฌํ ์ ์๋๋ก ํ๋ค.
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
result = []
left = right = 0
q = deque()
while right < len(nums):
# print("deque = ", q)
# print("result = ", result)
while q and nums[q[-1]] < nums[right]:
q.pop()
q.append(right)
if left > q[0]:
q.popleft()
if (right + 1) >= k:
result.append(nums[q[0]])
left += 1
right += 1
return result- ๐
deque๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ๋ํด์๋ ์๊ฒ ๋์๋ค.- ์ฝ์ ๊ณผ ์ญ์ ๊ฐ ๋ชจ๋ ๊ฐ๋ฅํ ์๋ฃ ๊ตฌ์กฐ์ด๋ฏ๋ก ์ต๋๊ฐ์ ์ฐพ๋๋ฐ ์๊ฐ ๋ณต์ก๋๋ฅผ ๋ง์ด ์์ก์๋จน์๊ฑฐ ๊ฐ๋ค.
4. What I Learned
References