码迷,mamicode.com
首页 > 其他好文 > 详细

[CareerCup] 5.7 Find Missing Integer 查找丢失的数

时间:2015-08-21 13:13:09      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

 

5.7 An array A contains all the integers from 0 to n, except for one number which is missing. In this problem, we cannot access an entire integer in A with a single operation. The elements of A are represented in binary, and the only operation we can use to access them is "fetch the jth bit of A[i]," which takes constant time. Write code to find the missing integer. Can you do it in 0(n) time?

 

这道题给我们一个0到n的数组,然后其中一个数丢失了,让我们找到这个数。一个比较容易想到的方法是先用高斯求和公式求出等差数列0到n的和,然后遍历数组求所有数字之和,那么差值就是结果。但是这个解法就没有用到高大上的位操作Bit Manipulation,也许也不是出题人想考察的方法。题目中说了所有的整型数都是以二进制数表示的,而且可以以O(1)的时间来访问任意一位,这也很明显的提示了我们用位操作。我们先来看一个n=13的例子,那么0到13的二进制数表示如下:

00000        00100        01000        01100
00001        00101        01001        01101
00010        00110        01010
00011        00111        01011

然后我们观察上面的数字的最低有效位Least Significant Bit (LSB),然后我们统计1和0的个数,我们可以得出一个规律,当n是奇数时,0和1的个数相等,当n是偶数时,0比1多一个。那么当我们移除一个数的话,就有下面四种情况:

 

 

class Solution {
public:
    int findMissing(vector<int> nums) {
        return findMissing(nums, 0);
    }
    int findMissing(vector<int> nums, int col) {
        if (nums.empty()) return 0;
        vector<int> oneBits, zeroBits;
        for (auto &a : nums) {
            if (fetch(a, col) == 0) zeroBits.push_back(a);
            else oneBits.push_back(a);
        }
        if (zeroBits.size() <= oneBits.size()) {
            int v = findMissing(zeroBits, col + 1);
            return (v << 1) | 0;
        } else {
            int v = findMissing(oneBits, col + 1);
            return (v << 1) | 1;
        }
    }
    int fetch(int n, int col) {
        return n & (int)pow(2, col);
    }
};

 

[CareerCup] 5.7 Find Missing Integer 查找丢失的数

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4747429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!