1057. Stack (30) - 剑指offer 数据流中的中位数

本文详细解释了如何使用数据结构如multiset来有效地计算数据流中的中位数,包括插入、删除和获取中位数的操作,并通过代码实例展示了实现过程。

题目描述

Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian – return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<= 105). Then N lines follow, each contains a command in one of the following 3 formats:

Push key
Pop
PeekMedian
where key is a positive integer no more than 105.

Output Specification:

For each Push command, insert key into the stack and output nothing. For each Pop or PeekMedian command, print in a line the corresponding returned value. If the command is invalid, print “Invalid” instead.

Sample Input:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
Sample Output:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid

题目地址

http://www.patest.cn/contests/pat-a-practise/1057

ac代码

/*
http://www.patest.cn/contests/pat-a-practise/1057
1057. Stack (30)

// 可以插入相同的元素
multiset<int> qmax; // 从小到大排列
// 从大到小排列 cmp return a>b 表示大的在前面
multiset<int, cmp> qmin; // 或用模版比较greater<int> #include <functional>

struct cmp // cmp本质上是一个比较的模版类 
{
    bool operator()(int a, int b)
    {
    return a > b;
    }
};
qmin.erase(qmin.find(t));
qmax.erase(qmax.begin()); // erase 所在的位置
qmin.insert(*qmax.begin()); *iterator 就是该值
*/
#include <stdio.h>
#include <iostream>  
#include <vector>  
#include <map>  
#include <set>  
#include <string>  
#include <string.h>
#include <algorithm>  
#include <sstream>
#include <iterator>
#include <queue>
#include <stack>
#include <functional>
using namespace std;

#define N 100001

struct cmp
{
    bool operator()(int a, int b)
    {
        return a > b;
    }
};

int main()
{
    //freopen("in.txt", "r", stdin);
    int n, k;
    while (scanf("%d", &n) != EOF)
    {
        int i;
        char stmp[15];

        // 可以插入相同的元素
        multiset<int> qmax; // 从小到大排列
        // 从大到小排列 cmp return a>b 表示大的在前面 
        multiset<int, cmp> qmin; // greater<int> #include <functional>

        stack<int> staNum;
        int midval = -1;
        for (i = 0; i < n; i++)
        {
            scanf("%s", stmp);
            if (stmp[1] == 'o') // Pop
            {
                if (staNum.empty())
                {
                    printf("Invalid\n");
                }
                else{
                    int t = staNum.top();
                    staNum.pop();
                    printf("%d\n", t);
                    // 找到并删除
                    if (t > *qmin.begin())
                    {
                        qmax.erase(qmax.find(t));
                    }
                    else{
                        qmin.erase(qmin.find(t));
                    }

                    if(!staNum.empty())
                    {
                        int len1 = qmin.size();
                        int len2 = qmax.size();
                        if (len1 < len2)
                        {
                            qmin.insert(*qmax.begin());
                            qmax.erase(qmax.begin()); // erase 所在的位置
                        }
                        else if(len1 - len2 >= 2){
                            qmax.insert(*qmin.begin());
                            qmin.erase(qmin.begin()); // erase 所在的位置
                        }

                        midval = *qmin.begin();
                    }

                }
            }
            else if (stmp[1] == 'u') // Push
            {
                int tmp;
                scanf("%d", &tmp);
                staNum.push(tmp);
                if (tmp <= midval)
                {
                    qmin.insert(tmp);
                }
                else{
                    qmax.insert(tmp);
                }

                int len1 = qmin.size();
                int len2 = qmax.size();
                if (len1 < len2)
                {
                    qmin.insert(*qmax.begin());
                    qmax.erase(qmax.begin()); // erase 所在的位置
                }
                else if (len1 - len2 >= 2){
                    qmax.insert(*qmin.begin());
                    qmin.erase(qmin.begin()); // erase 所在的位置
                }

                midval = *qmin.begin();
            }
            else{ //if (stmp[1] == 'e'){ // PeekMedian
                if (staNum.empty())
                {
                    printf("Invalid\n");
                }
                else{
                    printf("%d\n", midval);
                }
            }
        }
    }
    //printf("\n");
    return 0;
}

multiset基础用法

multiset<int> qmin;

qmin.insert(2);
qmin.insert(1);
cout << *qmin.begin() << endl; // 1
qmin.insert(2);
qmin.erase(qmin.begin());
qmin.insert(3);
cout << *qmin.begin() << endl; //2

multiset<int>::iterator it = qmin.begin();
while(it != qmin.end())
{
    cout << *it << " "; // 2, 2, 3
    ++it;
}
cout << endl;
struct cmp{
    bool operator()(int a,int b)
    {
        return a > b;   
    }
};

int main()
{
    //freopen("in.txt", "r", stdin);

    multiset<int,cmp> qmax;

    qmax.insert(2);
    qmax.insert(1);
    cout << *qmax.begin() << endl; // 2
    qmax.insert(2);
    qmax.erase(qmax.begin());
    qmax.insert(3);
    cout << *qmax.begin() << endl; //3

    multiset<int,cmp>::iterator it = qmax.begin();
    while(it != qmax.end())
    {
        cout << *it << " "; // 3, 2, 1
        ++it;
    }
    cout << endl;

    return 0;
}

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

C++ 测试程序

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <sstream>
#include <algorithm>
#include <set>

using namespace std;


struct cmp{
    bool operator()(int a, int b)
    {
        return a > b;
    }
};

priority_queue<int> pq_min;//可以插入重复的值, 每次取得的头部是最大的值

priority_queue<int,vector<int>,cmp> pq_max;//每次取得的头部是最小的值

int numCount = 0;

// 确保 pq_min的数量 >= pq_max的数量 且不能多于1个
void Insert(int num)
{
    numCount++;

    if (pq_min.empty())
        pq_min.push(num);
    else{

        int top = pq_min.top();
        if (num <= top)
        {
            pq_min.push(num);
        }
        else{
            pq_max.push(num);
        }

        int minSize = pq_min.size();
        int maxSize = pq_max.size();
        if (minSize < maxSize)
        {
            int maxTop = pq_max.top();
            pq_max.pop();
            pq_min.push(maxTop);
        }

        if (minSize - maxSize > 1)
        {
            int minTop = pq_min.top();
            pq_min.pop();
            pq_max.push(minTop);
        }

    }
}

double GetMedian()
{ 
    if (numCount % 2 == 0) //偶数
    {
        int num = pq_min.top() + pq_max.top();
        return 1.0 * num / 2;
    }
    else{ // 奇数
        return pq_min.top();
    }
}

int main()
{
    for (int i = 1; i < 5; i++)
    {
        Insert(i);
    }
    double num = GetMedian();

    cout << num << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值