일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Python
- iterator
- 715. Range Module
- 30. Substring with Concatenation of All Words
- 시바견
- data science
- t1
- kaggle
- Class
- Python Code
- LeetCode
- concurrency
- 43. Multiply Strings
- Protocol
- 109. Convert Sorted List to Binary Search Tree
- 315. Count of Smaller Numbers After Self
- 운영체제
- Convert Sorted List to Binary Search Tree
- Generator
- 컴퓨터의 구조
- shiba
- 밴픽
- Decorator
- 프로그래머스
- Substring with Concatenation of All Words
- DWG
- Python Implementation
- Regular Expression
- 파이썬
- attribute
Archives
- Today
- Total
Scribbling
LeetCode: 239. Sliding Window Maximum 본문
가장 먼저 떠오른 방법은 Priority Queue를 사용하는 것.
Time Complexity: O(N*logN)
import heapq
class PriorityQueue:
def __init__(self):
self.pq = []
self.removals = []
def insert(self, elem):
heapq.heappush(self.pq, -elem)
def gettop(self):
return -self.pq[0]
def remove(self, elem):
if elem == -self.pq[0]:
heapq.heappop(self.pq)
while self.removals and self.pq[0] == self.removals[0]:
heapq.heappop(self.pq)
heapq.heappop(self.removals)
else:
heapq.heappush(self.removals, -elem)
def length(self):
return len(self.pq)
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
ret = []
pq = PriorityQueue()
for i in range(len(nums)):
if pq.length() < k:
pq.insert(nums[i])
else:
ret.append(pq.gettop())
pq.remove(nums[i-k])
pq.insert(nums[i])
ret.append(pq.gettop())
return ret
풀리긴 하나 느리다...
다른 방법이 있을까?
아래 선생님의 설명을 참고하였다.
방법은 Monotonic Deque
Time Complexity: O(N)
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
from collections import deque
ret = []
q = deque()
for i, num in enumerate(nums):
if q and q[0] == i - k:
q.popleft()
while q and nums[q[-1]] < num:
q.pop()
q.append(i)
if i >= k - 1:
ret.append(nums[q[0]])
return ret
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 283. Move Zeroes (0) | 2021.12.25 |
---|---|
LeetCode: 234. Palindrome Linked List (0) | 2021.12.24 |
LeetCode: 218. The Skyline Problem (0) | 2021.12.22 |
LeetCode: 206. Reverse Linked List (0) | 2021.12.21 |
LeetCode: 202. Happy Number (0) | 2021.12.21 |