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 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 do it in 0 (n) time?
This problem gives us an array of 0 to N, and then one of the numbers is lost, let's find this number. A more easily thought method is to use the Gaussian summation formula to find the sum of arithmetic progression 0 to N, and then iterate through the array to find the sum of all the numbers, then the difference is the result. However, this solution does not use the high-bit operation bit manipulation, perhaps it is not the method that the author wants to examine. The title says that all of the integers are represented in binary numbers, and can be accessed with an O (1) time, which clearly hints at the use of bit operations. Let's take a look at a n=13 example, so the binary number from 0 to 13 is shown below:
00000 0010 0 01000 01100
00001 00101 01001 01101
00010 00110 01010
00011 00111 01011
Then we observe the lowest significant bit of the number above least significant bit (LSB), and then we count the number 1 and 0, we can draw a rule, when n is odd, the number of 0 and 1 is equal, when n is even, 0:1 more. So when we remove a number, there are four things:
classSolution { Public: intFindmissing (vector<int>nums) { returnFindmissing (Nums,0); } intFindmissing (vector<int> Nums,intCol) { if(Nums.empty ())return 0; Vector<int>Onebits, Zerobits; for(Auto &a:nums) { if(Fetch (A, col) = =0) Zerobits.push_back (a); ElseOnebits.push_back (a); } if(Zerobits.size () <=onebits.size ()) { intv = findmissing (zerobits, col +1); return(v <<1) |0; } Else { intv = findmissing (onebits, col +1); return(v <<1) |1; } } intFetchintNintCol) { returnN & (int) Pow (2, col); }};
[Careercup] 5.7 find Missing Integer for missing number