topic:
Given a sequence of n numbers from 0 , 1 , 2 , ..., n , find the number of 0 .. n that does not appear in the sequence. Case 1 Input: [ 3 , 0 , 1 ] Output: 2 Case 2 Input: [ 9 , 6 , 4 , 2 , 3 , 5 , 7 , 0 , 1 ] Output: 8 Precautions: Your algorithm should run with linear complexity. Can you implement it using only constant extra space complexity?
Problem solving ideas:
XOR XOR from 0 to n to get the result val, and then XOR val with each element in the array to get the result. The solution to the subproblem is similar to a number from 1 to n where a number appears twice, and the solution to find the number is the same.
code show as below:
class Solution { public: int missingNumber(vector<int>& nums) { int n = nums.size()+1; int res = 0; for(int i = 0;i < n; ++i){ res ^=i; } for(int i = 0;i < nums.size();++i){ res ^=nums[i]; } return res; } };
Solution two: