编程珠机 第二章 找出一个不在文件中一32位整数。

来源:互联网 发布:深渊巨口皮肤淘宝 编辑:程序博客网 时间:2024/06/06 03:34
给定一个最多包含40亿个随机排列的32位整数的顺序文件,找出一个不在文件中一32位整数。
该题目有2个问题,
1, 在内存足够的情况下, 使用位图法就可以  但是需要500多M的内存空间
2. 在没有足够内存的情况下 如何解决, 采用二分法。

思考: 是否可以从第三轮就得到想要的结果 不再循环下去,否则一直要等待bit最后一位循环结束!
第一轮
 splitA1  8 13
 splitA2  2 3 4 5
a = splitA1    calDeep 6
res = 8
第二轮
 splitA1 13
 splitA2 8   
res = 12       calDeep  8
a = splitA1
第三轮
splitA1 13
a = splitA1 
res = 14     calDeep  9
第四轮
splitA1 13
a = splitA1
res = 15     calDeep  10

最终的结果为15!



#include<stdio.h>

// 这个版本的问题是空间占用也很大, 另外需要2个数组。

int getNumber(int* a, int* splitA1, int* splitA2, int lenA, int bit)
{
    int res = 0;
    int i, A1n, A2n;
    int calDeep =1;
    while(bit-- > 0)
    {
        for(i = A1n = A2n =0; i < lenA; i++)
        {
            //if((a[i]>>(bit))==1)   此处有bug, 如果13 的话 13>>2 为3 在第二轮中还是不能进入到splitA1
            if((a[i] & (1<<bit)))
            {    
                splitA1[A1n++]=a[i];
            }else
                {    
                    splitA2[A2n++]=a[i];
                }
            calDeep++;
        }
        if(A1n <= A2n)
        {
            res += 1<< bit;
            a = splitA1;
            lenA = A1n;
        }else
            {
                a = splitA2;
                lenA = A2n;
            }
    }
    printf("The over all calculator deep is %d\n", calDeep);
    return res;
}
void main(){
    int a[6]= {2,3,4,5,8,13};
    int A1[3] ={};
    int    A2[3]= {};
    int res = getNumber(a,A1,A2,6,4);
    printf("find the num that is not stored is %d\n",res);
    
}


最新版本代码去掉了2个数组!

#include<stdio.h>
int getNumber(int* a, int lenA, int bit)
{
    int res = 0;
    int i, A1n, A2n;
    int calDeep =1;
    int countPre;
    int countNext;
    int* p = a;
    int n = bit;
    while(bit-- > 0)
    {
        for(i = countPre = countNext =0; i < lenA; i++)
        {
            if(*(p+i) & (1<<bit))
            {    
                countPre++;
            } else {
                countNext++;
            }
            calDeep++;
        }
        if (countPre <= countNext)
        {
            res += 1<< bit;
            p = a+countNext;
            lenA = countPre;
        } else {
            lenA = countNext;
        }
        printf("res = %d\n", res);
    }
    printf("The over all calculator deep is %d\n", calDeep);
    return res;
}
void main(){
    int a[6]= {2,3,4,5,8,15};
    int res = getNumber(a,6,4);
    printf("find the num that is not stored is %d\n",res);
    
}
原创粉丝点击