-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFindMedianfromDataStream_295.cpp
88 lines (73 loc) · 1.79 KB
/
FindMedianfromDataStream_295.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 295. Find Median from Data Stream
~ Link : https://leetcode.com/problems/find-median-from-data-stream/
*/
// Approach 1 (Using sorting)
/*
class MedianFinder {
private:
vector<int> nums;
public:
void addNum(int num) {
nums.emplace_back(num);
}
double findMedian() {
sort(nums.begin(), nums.end());
int n = nums.size();
if (n & 1)
return nums[n / 2];
else
return ((double)nums[(n / 2) - 1] + nums[n / 2]) / 2;
}
};
*/
// T.C. - O(nlogn)
// S.C. - O(n)
// Approach 2 (Using insertion sort)
/*
class MedianFinder {
private:
vector<int> nums;
public:
void addNum(int num) {
if (nums.size() == 0)
nums.emplace_back(num);
else
nums.insert(lower_bound(nums.begin(), nums.end(), num), num);
}
double findMedian() {
int n = nums.size();
if (n & 1)
return nums[n / 2];
else
return ((double)nums[(n / 2) - 1] + nums[n / 2]) / 2;
}
};
*/
// T.C. - O(logn) + O(n) = O(n)
// S.C. - O(n)
// Approach 3 (Using Min-Heap & Max-Heap)
class MedianFinder {
private:
priority_queue<int> pqmx;
priority_queue<int, vector<int>, greater<int> > pqmn;
public:
void addNum(int num) {
pqmx.push(num);
pqmn.push(pqmx.top());
pqmx.pop();
if (pqmx.size() < pqmn.size()) {
pqmx.push(pqmn.top());
pqmn.pop();
}
}
double findMedian() {
if (pqmx.size() > pqmn.size())
return pqmx.top();
else
return ((double) pqmx.top() + pqmn.top())/ 2;
}
};
// T.C. - O(logn)
// S.C. - O(n)