题解 | #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")

堆解法

全部评论

相关推荐

2024-12-21 01:36
电子科技大学 Java
牛客850385388号:员工福利查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务