6、在2.5亿个整数中找出不重复的整数,注,内存不足以容纳这2.5亿个整数。
方案1:采用2-Bitmap(每个数分配2bit,00表示不存在,01表示出现一次,10表示多次,11无意义)进行,共需内存内存,还可以接受。然后扫描这2.5亿个整数,查看Bitmap中相对应位,如果是00变01,01变10,10保持不变。所描完事后,查看bitmap,把对应位是01的整数输出即可。
方案2:也可采用与第1题类似的方法,进行划分小文件的方法。然后在小文件中找出不重复的整数,并排序。然后再进行归并,注意去除重复的元素。
7、腾讯面试题:给40亿个不重复的unsigned int的整数,没排过序的,然后再给一个数,如何快速判断这个数是否在那40亿个数当中?
与上第6题类似,我的第一反应时快速排序+二分查找。以下是其它更好的方法: 方案1:oo,申请512M的内存,一个bit位代表一个unsigned int值。读入40亿个数,设置相应的bit位,读入要查询的数,查看相应bit位是否为1,为1表示存在,为0表示不存在。(与第6题类似)
- // TestSTL.cpp : 定义控制台应用程序的入口点。
- //
-
- #include "stdafx.h"
- #include
- #include
- #include
- #include
- using namespace std;
-
- #define TestArrayLen (100)//多少个数
- #define RangeValue (100)//取值范围
- #define BitsPerInt (32)//Int类型所占位数,int类型改为位存储
- #define BitsPerNum (BitsPerInt/2)//一个数用2位存储==原一个int类型的整数空间(4字节)可以存储16个数
- #define BitArrayLen (1+RangeValue/BitsPerNum)//所需位数组长度
-
- //bitset
bitArray[BitArrayLen]; - bitset
* bitArray=new bitset[BitArrayLen]; -
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- int* data=new int[TestArrayLen];
- memset(data,0,TestArrayLen);
-
- //生成1-TestArrayLen之间的随机数
- for (int i=0; i
- {
- srand(GetTickCount());
- data[i]=rand()%RangeValue+1;
- cout << data[i] << " ";
- if ((i+1)%10==0)
- {
- cout << endl;
- }
- }
- int roundNum=0;//取整
- int remainNum=0;//取余
- //数据在位图中进行存储,即位图排序
- for (int j=0; j
- {
- roundNum=(data[j]-1)/BitsPerNum;
- remainNum=(data[j]-1)%BitsPerNum;
- if (bitArray[roundNum][remainNum*2]==1 || bitArray[roundNum][remainNum*2+1]==1)//如果为01,设为10;本来为10,不变
- {
- bitArray[roundNum].set(remainNum*2+1,1);
- bitArray[roundNum].set(remainNum*2,0);
- }
- else//如果为00,设为01
- {
- bitArray[roundNum].set(remainNum*2,1);
- }
- }
- //位图排数,输出所有重复的数
- cout << "所有重复的数:";
- for (int k=0;k
- {
- for (int l=0;l
- {
- if (bitArray[k][2*l+1]==1)
- {
- cout << k*BitsPerNum+l+1 << " ";
- }
- }
- }
- cout << endl;
-
- //位图排数,输出所有不重复的数
- cout << "所有不重复的数:";
- for (int m=0;m
- {
- for (int l=0;l
- {
- if (bitArray[m][2*l]==1)
- {
- cout << m*BitsPerNum+l+1 << " ";
- }
- }
- }
- cout << endl;
-
- system("pause");
- return 0;
- }
大家有更好的办法欢迎指出。。。大家有更好的办法欢迎指出。。。大家有更好的办法欢迎指出。。。大家有更好的办法欢迎指出。。。大家有更好的办法欢迎指出。。。
注:本文转载自blog.csdn.net的brk1985的文章"https://blog.csdn.net/brk1985/article/details/18732267"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
评论记录:
回复评论: