File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 풀이 :
3+ maxHeap과 minHeap 사용
4+
5+ heap에 담긴 총 수 : N
6+
7+ addNum()
8+ 작은 수 집합은 maxHeap, 큰 수 집합은 minHeap에 담는다
9+ minHeap과 maxHeap의 개수차이를 1로 유지하면서 addNum
10+
11+ TC : O (log N)
12+ 힙에 넣고 뺄 때 O (logN) 의 시간 소요
13+
14+ SC : O (N)
15+ 총 힙 크기는 N에 비례
16+
17+ findMedian()
18+ 더 크게 유지되는 것은 minHeap이므로 둘 의 개수가 같지 않을경우(총 홀수개) minHeap.top() 리턴
19+ 같을 경우 총개수가 짝수개이므로 두 힙.top()의 평균을 리턴
20+
21+ TC : O (1)
22+ 각 힙에서 root값 확인은 O(1)의 시간 소요
23+ SC : O (1)
24+ */
25+
26+ #include < queue>
27+ #include < vector>
28+ using namespace std ;
29+
30+ class MedianFinder {
31+ public:
32+ priority_queue<int > maxHeap;
33+ priority_queue<int , vector<int >, greater<int >> minHeap;
34+
35+ MedianFinder () {
36+
37+ }
38+
39+ void addNum (int num) {
40+ if (minHeap.empty () || num >= minHeap.top ())
41+ minHeap.push (num);
42+ else
43+ maxHeap.push (num);
44+
45+ if (minHeap.size () > maxHeap.size () + 1 ) {
46+ maxHeap.push (minHeap.top ());
47+ minHeap.pop ();
48+ }
49+ else if (maxHeap.size () > minHeap.size ()) {
50+ minHeap.push (maxHeap.top ());
51+ maxHeap.pop ();
52+ }
53+ }
54+
55+ double findMedian () {
56+ if (maxHeap.size () == minHeap.size ())
57+ return static_cast <double >(maxHeap.top () + minHeap.top ()) / 2 ;
58+ else
59+ return minHeap.top ();
60+ }
61+ };
62+
63+ /* *
64+ * Your MedianFinder object will be instantiated and called as such:
65+ * MedianFinder* obj = new MedianFinder();
66+ * obj->addNum(num);
67+ * double param_2 = obj->findMedian();
68+ */
You can’t perform that action at this time.
0 commit comments