Skip to content

Commit 80c82a8

Browse files
committed
solve(w13): 295. Find Median from Data Stream
1 parent b474b7d commit 80c82a8

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# https://leetcode.com/problems/find-median-from-data-stream/
2+
3+
import heapq
4+
5+
class MedianFinder:
6+
"""
7+
[Time Complexity]
8+
- addNum(): O(logn) (heappush / heappop -> ํž™ ์†์„ฑ ์œ ์ง€ ์œ„ํ•ด ํŠธ๋ฆฌ ๋†’์ด๋งŒํผ swap => sift-up / sift-down)
9+
- findMedian(): O(1)
10+
11+
[Approach]
12+
findMedian์„ O(1)์— ์ˆ˜ํ–‰ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” addNum์„ ํ•  ๋•Œ๋งˆ๋‹ค ๋ฐ์ดํ„ฐ๋ฅผ ์ž‘์€ ๋ถ€๋ถ„ / ํฐ ๋ถ€๋ถ„์œผ๋กœ ์ ˆ๋ฐ˜์”ฉ ๋‚˜๋ˆ„์–ด์„œ ์œ ์ง€ํ•ด์•ผ ํ•œ๋‹ค.
13+
์ด๋•Œ, ๊ฐ€๋Šฅํ•œ ์ผ€์ด์Šค๋ณ„ median์„ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
14+
- ๋‘ ์ ˆ๋ฐ˜์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™๋‹ค๋ฉด median = ((์ž‘์€ ๋ถ€๋ถ„์˜ ๊ฐ€์žฅ ํฐ ๊ฐ’) + (ํฐ ๋ถ€๋ถ„์˜ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’)) / 2
15+
- ๋‘ ์ ˆ๋ฐ˜์˜ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋‹ค๋ฉด (ํฐ ๋ถ€๋ถ„์˜ ๊ธธ์ด๊ฐ€ ์ž‘์€ ๋ถ€๋ถ„์˜ ๊ธธ์ด๋ณด๋‹ค 1 ํฐ ๊ฒฝ์šฐ๋ผ๊ณ  ๊ฐ€์ •) median = (ํฐ ๋ถ€๋ถ„์˜ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’)
16+
๋”ฐ๋ผ์„œ ์ž‘์€ ๋ถ€๋ถ„ / ํฐ ๋ถ€๋ถ„์„ ๊ฐ๊ฐ max heap / min heap์œผ๋กœ ๊ด€๋ฆฌํ•˜๋ฉฐ, addNum ํ•  ๋•Œ๋งˆ๋‹ค ๋‹ค์Œ์€ ๋™์ž‘์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.
17+
- ๋‘ ์ ˆ๋ฐ˜์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™๋‹ค๋ฉด, ์ž‘์€ ๋ถ€๋ถ„์— push -> pop ํ•œ ๊ฒฐ๊ณผ๋ฅผ ํฐ ๋ถ€๋ถ„์— push
18+
- ๋‘ ์ ˆ๋ฐ˜์˜ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋‹ค๋ฉด, ํฐ ๋ถ€๋ถ„์— push -> pop ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ž‘์€ ๋ถ€๋ถ„์— push
19+
(ํŒŒ์ด์ฌ์—์„œ max heap์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” min heap์— ๋ถ€ํ˜ธ ๋ฐ˜์ „์ธ ์ˆ˜๋ฅผ ๋„ฃ์Œ์œผ๋กœ์จ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์— ์œ ์˜ํ•œ๋‹ค!)
20+
"""
21+
22+
def __init__(self):
23+
self.lo = [] # ์ ˆ๋ฐ˜ ์ค‘ ์ž‘์€ ๋ถ€๋ถ„
24+
self.hi = [] # ์ ˆ๋ฐ˜ ์ค‘ ํฐ ๋ถ€๋ถ„
25+
26+
def addNum(self, num: int) -> None:
27+
if len(self.lo) == len(self.hi):
28+
heapq.heappush(self.hi, -heapq.heappushpop(self.lo, -num)) # heappushpop: heap์„ ํ•œ ๋ฒˆ๋งŒ
29+
else:
30+
heapq.heappush(self.lo, -heapq.heappushpop(self.hi, num))
31+
32+
def findMedian(self) -> float:
33+
if len(self.lo) == len(self.hi):
34+
return (-self.lo[0] + self.hi[0]) / 2
35+
else:
36+
return self.hi[0]
37+
38+
# Your MedianFinder object will be instantiated and called as such:
39+
# obj = MedianFinder()
40+
# obj.addNum(num)
41+
# param_2 = obj.findMedian()

0 commit comments

Comments
ย (0)