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


    // ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    #include<algorithm>
    #include<numeric>
    #include<list>
    #include<iterator>
    #include<queue>
    #include<stack>
    #include<algorithm>
    #include<forward_list>
    using namespace std;
    
    
    
    
    
    
    class Solution {
    public:
    	vector <int> fl;//从小到大排序
    	int count = 0;
    	void Insert(int num)
    	{
    		auto it = fl.begin();
    		while (it != fl.end())
    		{
    			if (num < *it) break;
    			++it;
    		}
    		fl.insert(it, num); //在迭代器it前面插入一个元素
    		++count;
    	}
    
    	double GetMedian()
    	{
    		if (count % 2 == 1)
    			return fl[count /2];
    		else
    			return (fl[count / 2 - 1]+ fl[count / 2 ])/2.0;
    		
    	}
    
    
    
    
    };
    
    int main()
    {
    
    	Solution so;
    	cout << "[5,2,3,4,1,6,7,0,8]" << endl;
    	so.Insert(5);
    	cout << so.GetMedian() << "  ";
    	so.Insert(2);
    	cout << so.GetMedian() << "  ";
    	so.Insert(3);
    	cout << so.GetMedian() << "  ";
    	so.Insert(4);
    	cout << so.GetMedian() << "  ";
    	so.Insert(1);
    	cout << so.GetMedian() << "  ";
    	so.Insert(6);
    	cout << so.GetMedian() << "  ";
    	so.Insert(7);
    	cout << so.GetMedian() << "  ";
    	so.Insert(0);
    	cout << so.GetMedian() << "  ";
    	so.Insert(8);
    	cout << so.GetMedian() << "  ";
    	cout << endl;
    
    
    
    	//so.getData(T);
    	//cout << "qu 队列中的值:" << endl;
    	//so.print();
    	//cout << endl;
    
    
    	return 0;
    }
    

    注意:我在做这道题的时候,是利用vector存储从小到大的元素,每次,都是取vector的中位数
    此方法还有另一个解法,就是利用堆栈,效率更高,以后需要多学习。

  • 相关阅读:
    6、linux中同步、互斥、阻塞(原子操作、信号量、阻塞)
    lightOJ-1199 Partitioning Game (SG函数)
    HDU-1013 Digital Roots
    HDU-1004 Let the Balloon Rise (STL map)
    HDU-1020 Encoding (字符串)
    POJ-2524 Ubiquitous Religions (并查集)
    POJ-1988 Cube Stacking (带权并查集)
    POJ-2236 Wireless Network (并查集)
    HDU-1002 A + B Problem II (模拟大数相加)
    HDU-1829 A Bug's Life (种类并查集)
  • 原文地址:https://www.cnblogs.com/wdan2016/p/6000384.html
Copyright © 2020-2023  润新知