File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change 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+ */
You can’t perform that action at this time.
0 commit comments