寻找中位数

寻找中位数

TimeLimit:1000MS  MemoryLimit:128MB

64-bit integer IO format:%lld

已解决 | 点击收藏

×

收藏题目

备注

Close确定

Problem Description

这题温暖大家的心(手动滑稽.jpg我看能收割多少个wa)

给定n个整数,求这些整数的中位数。

注意:若n为偶数,输出从小到大排序后最中间的两个数的平均数向下取整的结果.

其中向下取整的定义 :x的向下取整 = 不大于x的最大整数

Input

单组数据

第一行包含一个整数n,代表有n的整数

接下来一行有n个整数 a1,a2,a3……an

1<=n<=106

保证所有整数都在int 范围内。

后台共有4组n=1e6级别的大数据。

测评机的测评时间,是累加所有测试点的耗时的

Output

输出一个整数代表中位数

SampleInput

4 -4 -2 -1 -3

SampleOutput

-3
#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<bitset>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define eps (1e-8)
#define MAX 0x3f3f3f3f
#define u_max 1844674407370955161
#define l_max 9223372036854775807
#define i_max 2147483647
#define re register
#define pushup() tree[rt]=tree[rt<<1]+tree[rt<<1|1]
#define nth(k,n) nth_element(a,a+k,a+n);  // 将 第K大的放在k位
using namespace std;

inline int read(){
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' & c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int n,a[2000005];
int main() {
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        a[i]=read();
    }
    if(n&1){
        nth(n/2,n);
        printf("%d\n",a[n/2]);
    }
    else{
        nth(n/2-1,n);
        double s1=(double)a[n/2-1];
        nth(n/2,n);
        double s2=(double)a[n/2];
        printf("%d\n",(int)floor((s1+s2)/2.0));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/black_horse2018/article/details/83040377