维护一个链表,插入,然后取,就很简单了
数据流中的中位数
http://www.nowcoder.com/questionTerminal/9be0172896bd43948f8a32fb954e1be1
随便乱写的,代码很乱也不管了
class Solution { public: struct linklist{ int val; linklist *next; linklist(int x): val(x),next(nullptr){ } }; linklist *head = new linklist(0); int size = 0; void Insert(int num){ linklist *ptr = head; linklist *pre = ptr; if(size == 0){ head -> val = num; size ++; return; } while(ptr && num > ptr->val){ pre = ptr; ptr = ptr -> next; } if(pre == ptr){ linklist *tmp = new linklist(num); tmp->next = ptr; size ++; head = tmp; } else{ linklist *tmp = new linklist(num); tmp->next = ptr; pre->next = tmp; size++; } } double GetMedian(){ linklist *nptr = head; double ret=0; if(size%2 == 1){ for(int i=0;i<size/2;i++){ nptr = nptr->next; } return nptr->val; } else{ for(int i=0;i<size/2-1;i++){ nptr = nptr->next; } ret += nptr->val; nptr = nptr->next; ret += nptr->val; ret /= 2; return ret; } } };