题目:
随机生成一些数字,并保存到一个(可扩展的)数组中,如何跟踪数组的中位数?
题解:
用multiset分别实现最大堆和最小堆,最大堆保存数组的前半部分,最小堆保存数组的后半部分,每次添加新数字时和堆顶元素比较。同时保证两个堆的元素个数之差不超过1.
//
// main.cpp
// Combination
//
// Created by on 14-2-3.
// Copyright (c) 2014年 . All rights reserved.
//
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef struct {
bool operator()( int i, int j) {
return i < j;
}
} Increase;
typedef struct {
bool operator()( int i, int j) {
return i >= j;
}
} Decrease;
typedef multiset<int, Increase> minHeap;
typedef multiset<int, Decrease> maxHeap;
class Solution {
public:
void FindMedian()
{
cout << "Please enter the number of integers in your array:";
int count;
cin >> count;
int i = 0;
srand(static_cast<unsigned int>(time(0)));
maxHeap heap1;
minHeap heap2;
while( i < count )
{
int temp = rand()%100;
cout << temp << " is added into the integer array" << endl;
if(!heap1.size() && !heap2.size())
{
heap1.insert(temp);
i++;
continue;
}
if(temp > *heap1.begin())
{
heap2.insert(temp);
if(static_cast<int>(heap1.size() - heap2.size()) >= 2)
{
int temp = *heap1.begin();
heap1.erase(heap1.begin());
heap2.insert(temp);
}
else if(static_cast<int>(heap2.size() - heap1.size()) >= 2)
{
int temp = *heap2.begin();
heap2.erase(heap2.begin());
heap1.insert(temp);
}
}
else{
heap1.insert(temp);
if(static_cast<int>(heap1.size() - heap2.size()) >= 2)
{
int temp = *heap1.begin();
heap1.erase(heap1.begin());
heap2.insert(temp);
}
else if(static_cast<int>(heap2.size() - heap1.size()) >= 2)
{
int temp = *heap2.begin();
heap2.erase(heap2.begin());
heap1.insert(temp);
}
}
cout << "Intergers in the first heap (max heap) are:";
for(auto iter: heap1)
cout << iter << " ";
cout << endl;
cout << "Intergers in the second heap (max heap) are:";
for(auto iter: heap2)
cout << iter << " ";
cout << endl;
cout << "The median of the entire integer array is: ";
if( heap1.size() > heap2.size())
cout << *heap1.begin() << endl << endl;
else if(heap1.size() < heap2.size())
cout << *heap2.begin() << endl << endl;
else
cout << (*heap1.begin() + *heap2.begin())/2 << endl << endl;
i++;
}
}
};
int main(int argc, const char * argv[])
{
// insert code here...10
Solution a;
a.FindMedian();
return 0;
}