题解 | #数据流中的中位数#

数据流中的中位数

http://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1

// 数据流中位数: // 这种类型题目(求最大的K个数,最小的K个数) // 中位数其实就是最大的N/2个 // 首先想到优先队列,很适合处理这类需求

class Solution { public: void Insert(int num) { if(maxHeap.empty() && minHeap.empty()){ maxHeap.push(num); minHeap.push(num); flag = 1; } else { if(flag == 1) { if(num < maxHeap.top()) { maxHeap.pop(); maxHeap.push(num); }else{ minHeap.pop(); minHeap.push(num); } flag = 0; } else{ if(num < maxHeap.top()) { minHeap.push(maxHeap.top()); maxHeap.push(num); }else if(num > minHeap.top()){ maxHeap.push(minHeap.top()); minHeap.push(num); }else{ maxHeap.push(num); minHeap.push(num); } flag = 1; } } }

double GetMedian() { 
    double res;
    res = (maxHeap.top() + minHeap.top()) / 2;
    return res;
}

private: priority_queue<double, vector, less> maxHeap; priority_queue<double, vector, greater> minHeap; int flag; };

全部评论

相关推荐

点赞 评论 收藏
分享
宇算唯航:目测实缴资本不超100W的小公司
点赞 评论 收藏
分享
06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 11:35
程序员小白条:话太多,没实力和学历,差不多回答回答就行了,身份地位不一样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务