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

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?

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

 N为偶数，0比1多一个 N为奇数，0和1个数相等 移除0 0和1个数相等 0比1个数少 移除1 0比1个数多 0比1个数多

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

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

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

01011

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);
}
};

posted @ 2015-08-21 11:42  Grandyang  阅读(1997)  评论(0编辑  收藏  举报