-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathfindMedianFromDataStream.cpp
98 lines (87 loc) · 2.36 KB
/
findMedianFromDataStream.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
89
90
91
92
93
94
95
96
97
98
class MedianFinder {
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
private:
double getMedian(ListNode* head) {
if(head->next == NULL){
return head->val;
}
else {
ListNode * fast = head->next;
ListNode * slow = head;
while(fast != NULL){
fast = fast->next;
if(fast==NULL){
return (double)(slow->val + slow->next->val) / (double)2;
}
fast = fast->next;
slow = slow->next;
}
return slow->val;
}
}
public:
ListNode* head = NULL;
ListNode* tail = NULL;
MedianFinder() {
// ListNode* head = NULL;
// ListNode* tail = NULL;
}
void addNum(int num) {
ListNode* node = new ListNode(num);
//empty list
if(head == NULL) {
head = node;
tail = node;
return;
}
//one node
else if(head->next == NULL){
if(head->val <= num){
head->next = node;
tail = node;
}else{
node->next = head;
head = node;
tail = node->next;
}
}
//multiple node
else if(tail->val <= num){
tail->next = node;
tail = node;
}
else{
if(tail->val > num && head->val >= num){
node->next = head;
head = node;
}else{
ListNode * curr = head->next;
ListNode * prev = head;
while(curr!=NULL){
if(curr->val >= num){
prev->next = node;
node->next = curr;
break;
}
prev = curr;
curr = curr->next;
}
}
}
}
double findMedian() {
return getMedian(head);
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/