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