-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Linked list approach Leetcode Hard Problem 295. Find Median from Data Stream
- Loading branch information
Showing
1 changed file
with
98 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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(); | ||
*/ |