现在有1千万个随机数,随机数的范围在1到1亿之间。现在要求写出一种算法,将1到1亿之间没有在随机数中的数求出来。

来源:互联网 发布:金融培训机构 知乎 编辑:程序博客网 时间:2024/05/17 01:32
#include <iostream>using namespace std;//1亿#define BILL (1000*1000*1000)//用int的32位存储标志: 1亿/32bit#define FLAGS 3125000//随机数个数#define RANCOUNT (1000*10000)#define BIT_SIZE 32void printArray(int* arr, int len) {cout << "数组:" << endl;for (int i = 0; i < len; ++i) {cout << arr[i] << " ";}cout << endl;}int* initRandom(int len, int range) {int* randoms = new int[len];srand(unsigned(time(0)));for (int i = 0; i < len; i++) {randoms[i] = rand() % range;}return randoms;}void initTable(int* table, int size) {for (int i = 0; i < size; ++i) {table[i] = 1 << i;}}void mapRandomsIntoFlags(int* randoms, int ranLen, int* flag, int* table) {/* * 将随机数转化存入flag数组,先找到在哪个flag[i]元素,到找到里面对应的bit位,用按位或操作插入 * table[i]=1<<i */for (int i = 0; i < ranLen; ++i) {int id = (randoms[i] - 1) / BIT_SIZE;flag[id] |= table[(randoms[i] - 1) % BIT_SIZE];}}void findNotFlag(int* flags, int bill, int* table) {/*判断数是否存在,先找到数对应哪个flag[i],再找到里面对应的bit位,用按位与操作判断是否存在*/for (int i = 1; i <= bill; ++i) {int id = (i - 1) / BIT_SIZE;if (!(flags[id] & table[(i - 1) % BIT_SIZE])) {cout << i << endl;}}}/*给出具体代码机器问题无法验证*/int main() {//1千万个随机数,随机数的范围在1到1亿之间int* randoms = initRandom(RANCOUNT, BILL);//用bit来标记数是否存在,int有32bit,则有1亿/32=3125000int*flags = new int[FLAGS];memset(flags, 0, FLAGS * sizeof(int));//存在2^0,2^1....2^31标记用来操作指定bitint* table = new int[BIT_SIZE];initTable(table, BIT_SIZE);mapRandomsIntoFlags(randoms, RANCOUNT, flags, table);findNotFlag(flags, BILL, table);return 0;}

1 0
原创粉丝点击