题解 | #Median#

Median

https://www.nowcoder.com/practice/b5da3f56557f42978ca87afedbd85fbe

#include <bits/stdc++.h>
#include <queue>
using namespace std;

int main() {
    int a;
    while (cin >> a) { // 注意 while 处理多个 case
        priority_queue<long> maxheap;
        priority_queue<long, vector<long>, greater<>> minheap;
        long t, b;
        while (a--) {
            cin >> t;
            if (maxheap.empty() || t <= maxheap.top()) maxheap.push(t);
            else minheap.push(t);
            while (maxheap.size() > minheap.size() + 1) {
                minheap.push(maxheap.top());
                maxheap.pop();
            } 
            while (maxheap.size() < minheap.size()) {
                maxheap.push(minheap.top());
                minheap.pop();
            }
        }
        cin>>b;
        while (b--) {
            cin >> t;
            if (maxheap.empty() || t <= maxheap.top()) maxheap.push(t);
            else minheap.push(t);
            while (maxheap.size() > minheap.size() + 1) {
                minheap.push(maxheap.top());
                maxheap.pop();
            } 
            while (maxheap.size() < minheap.size()) {
                maxheap.push(minheap.top());
                minheap.pop();
            }
        }
        cout<<maxheap.top()<<endl;
       // cout<<endl<<maxheap.size()<<' '<<maxheap.top()<<endl;
       // cout<<endl<<minheap.size()<<' '<<minheap.top()<<endl;
    }
}
// 64 位输出请用 printf("%lld")

堆解法

全部评论

相关推荐

01-11 08:47
门头沟学院 Java
羊村你懒哥1:如果不放毕业,我只能说导师是自己选的,错在你选了个垃圾导师,不在你实习
点赞 评论 收藏
分享
咪咪虫:小厂神人多,我昨天早上那个深圳500-1000人的厂,面试官迟到10分钟进来第一句话是:居然是个妹子,然后一直说自己没有准备什么的,全程八股都是支支吾吾的问。下午那个线下的广州280人的厂,二轮技术面一直在问我数据结构、操作系统、计算机网络,还问我高考多少分、为什么不上课、为什么住在学校外面、是什么时候高考的。。。脸上就是质疑和不屑,俩个体验感奇差
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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