有5亿个int范围的数字,量太大不能直接存放到内存下,如何处理可以找出中位数

  一般这种问题,可以考虑用分支的思想。

  1、由于不能直接放在内存里,先将这int范围的数字划分成2^16个区,第一个区的范围是[0 , (2^32-1) / (2^16)),以此类推。

  2、然后读入数据,分别将其累加到相应的分区。

  3、依次统计分区,读到累加数字个数大于等于2.5亿的时候,说明中位数在这个分区。

  4、重新读取所有数据,添加在这个分区范围的数据到数组中,对该数组排序就可以得到中位数了。

  

//有5亿个数字,量太大不能直接存放到内存下,如何处理可以找出中位数

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;

int hash[128*128];
int shu[1000000];

int main(){
    int i,n=1<<32-1,m=128*128,temp;
    double second;

    for(i=0;i<m;i++){
        hash[i]=0;
    }

    for(i=0;i<i;i++){
        scanf("%d",&temp);
        second=m*temp/n;
        hash[(int)second]++;
    }

    int add=0 , end = n>>1;
    for(i=0;i<m;i++){
        add+=hash[i];
        if(add >= end){
            break;
        }
    }

    int left = (int) (n*1.0/m * (i-1));
    int right= (int) (n*1.0/m * i);
    int num=0;
    for(i=0;i<n;i++){
        scanf("%d",&temp);
        if(temp>=left && temp<=right){
            shu[add]=temp;
            add++;
        }
    }

    sort(&shu[0],&shu[add]);
    
    if(add%2 == 0)
        printf("%d\n",(shu[add/2-1]+shu[add/2])/2);
    else
        printf("%d\n",shu[add/2]);

    return 0;
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-29
  • 2022-12-23
猜你喜欢
  • 2021-07-12
  • 2022-12-23
  • 2021-08-29
  • 2021-12-20
  • 2022-02-09
  • 2021-06-07
  • 2021-09-25
相关资源
相似解决方案