数组中位数

#include 
#include 
#include 
#include 
#include 
using namespace std;

double search_mid_num(vector& num){
    priority_queue, less<>> q;
    bool odd_flag = true;
    if(num.size() % 2 == 0)
        odd_flag = false;
    if(odd_flag){
        for(int i = 0; i <= num.size() / 2; ++i){
            q.push(num[i]);
        }
        for(int i = num.size() / 2 + 1; i < num.size(); ++i){
            if(num[i] < q.top()){
                q.pop();
                q.push(num[i]);
            }
        }
        return q.top();
    }
    else{
        for(int i = 0; i <= num.size() / 2; ++i){
            q.push(num[i]);
        }
        for(int i = num.size() / 2 + 1; i < num.size(); ++i){
            if(num[i] < q.top()){
                q.pop();
                q.push(num[i]);
            }
        }
        int num1 = q.top();
        q.pop();
        int num2 = q.top();
        return (double)(num1 + num2) / 2;
    }
}

int main(){
    vector input = {5,4};
    cout << search_mid_num(input) << endl;
    return 0;
}

 

你可能感兴趣的:(面试)