Skip to content

Commit b00d6aa

Browse files
committed
Solution 5
1 parent 08d3978 commit b00d6aa

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

find-median-from-data-stream/flynn.go

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
풀이
3+
- 이진탐색을 이용합니다
4+
Big O
5+
- N: 현재 MedianFinder.nums의 크기
6+
- AddNum
7+
- Time complexity: O(N)
8+
- bisect -> O(logN)
9+
- slices.Insert -> O(N)
10+
- Space complexity: O(1)
11+
- FindMedian
12+
- Time complexity: O(1)
13+
- Space complexity: O(1)
14+
*/
15+
16+
import "slices"
17+
18+
type MedianFinder struct {
19+
nums []int
20+
}
21+
22+
func Constructor() MedianFinder {
23+
mf := MedianFinder{}
24+
mf.nums = make([]int, 0)
25+
return mf
26+
}
27+
28+
func (this *MedianFinder) AddNum(num int) {
29+
n := len(this.nums)
30+
if n == 0 {
31+
this.nums = append(this.nums, num)
32+
} else {
33+
idx := bisectLeft(this.nums, num)
34+
this.nums = slices.Insert(this.nums, idx, num)
35+
}
36+
}
37+
38+
func (this *MedianFinder) FindMedian() float64 {
39+
n := len(this.nums)
40+
if n%2 == 0 {
41+
return (float64(this.nums[n/2-1]) + float64(this.nums[n/2])) / 2
42+
} else {
43+
return float64(this.nums[n/2])
44+
}
45+
}
46+
47+
// ----- Helper -----
48+
func bisectLeft(arr []int, x int) int {
49+
lo := 0
50+
hi := len(arr)
51+
for lo < hi {
52+
mid := lo + (hi-lo)/2
53+
if arr[mid] < x {
54+
lo = mid + 1
55+
} else {
56+
hi = mid
57+
}
58+
}
59+
return lo
60+
}
61+
62+
/**
63+
* Your MedianFinder object will be instantiated and called as such:
64+
* obj := Constructor();
65+
* obj.AddNum(num);
66+
* param_2 := obj.FindMedian();
67+
*/

0 commit comments

Comments
 (0)