Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
解题思路:
题意为找出0~n中缺少的那个数。要求O(n)的时间复杂度和O(1)的空间复杂度。
若采用排序查找的办法,则需要O(nlogn)的时间。
若采用hash的办法,则需要O(n)的空间复杂度。
采用位操作的办法。对数组中数的二进制位的1进行计数。然后对0~n中的二进制位的1进行计数。则两次计数的差则是missing number贡献的。
class Solution {
public:
int missingNumber(vector<int>& nums) {
vector<int> bitCount(sizeof(int) * 8, 0); //n + 1个数中的bit计数
vector<int> missingBitCount(sizeof(int) * 8, 0); //n个数中的bit计数
int len = nums.size();
for(int i=0; i<len; i++){
int j = 0;
int num = nums[i];
while(num){
if(num & 1){
missingBitCount[j]++;
}
j++;
num = num >> 1;
}
}
for(int i = 0; i<=len; i++){
int j = 0;
int num = i;
while(num){
if(num & 1){
bitCount[j]++;
}
j++;
num = num >> 1;
}
}
int result = 0;
for(int i = sizeof(int) * 8 - 1; i>=0; i--){
result = result << 1;
result += bitCount[i] - missingBitCount[i];
}
return result;
}
};