• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
My Blog@github像少年啦飞驰
{关注大规模数据处理(MapReduce)J2EE等技术}
博客园    首页    新随笔    联系   管理    订阅  订阅
一道百度笔试题

在看百度2013校园招聘笔试题,发现以下这道题有一定的思考价值。
题目:有20个数组,每个数组有500个元素,并且是有序排列好的,现在在这20*500个数中找出排名前500的数。

这道题一看就知道是个TopK的问题。解决这个问题思路如下:数组是有序的(假设是升序),我们要利用这个特性。首先构造一个大根堆(大小为数组个数即20),将每个数组当前最大的数放入堆中,然后取出大根堆的根,使用一个统计数组(大小为每个数组的长度即500)保存这个数,将这个数从大根堆中删除,接着再向大根堆中放入刚才删除的那个数的上一个数(数组是有序的),如此反复直到统计数组满了为止。

#include <iostream>
#include<cstdlib>
#include <set>
#include <algorithm>

using namespace std;

const int N = 20;
const int M = 500;
int a[N][M];//二维数组存放测试数据

struct node{
    int *p; //指向数组中末尾
};
struct classcomp{
    bool operator()(const node& left,const node& right)   //降序
    {
        return *left.p>*right.p;
    }
};

typedef multiset<node,classcomp> nodeSet;
typedef multiset<node,classcomp>::iterator setIterator;
int out_put[M];
int out_count=0;

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

void findTopK(int (&a)[N][M],nodeSet& nodeSet)
{
    node nodeArray[N];
    for(int i=0;i<N;i++)
    {
        nodeArray[i].p = &a[i][M-1];//指向每个数组的末尾即每个数组最大的数
    }
    for(int i=0;i<N;i++)
    {
        nodeSet.insert(nodeArray[i]);
    }
    while(out_count<M)
    {
        setIterator iteratorGreatest = nodeSet.begin();
        node n = *iteratorGreatest;//获取大根
        out_put[out_count++] = *n.p;//保存
        nodeSet.erase(iteratorGreatest);//删除
        n.p = n.p--;//指针向前移动
        nodeSet.insert(n);//插入
    }
    for(int i=0;i<M;i++)
    {
        cout<<out_put[i]<<" ";
    }
}

int main()
{
    int i,j;
    //随机生成数据
    for(i=0;i<N;i++)
    {
        for(j=0;j<M;j++)
        {
            a[i][j]=rand()%256;
        }

    }
    //排序
    for(i=0;i<N;i++)
    {
        qsort(&a[i][0],M,sizeof(int),compare);
    }

    nodeSet nodeSet;
    findTopK(a,nodeSet);
}

 

作者:像少年啦飞驰
出处:http://www.cnblogs.com/flyoung2008/
Blog:http://www.flyoung.me
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
分享到: 更多
posted on 2013-09-17 14:46  像少年啦飞驰  阅读(2681)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3