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?
Solution 1: sum(0,1,...,n)-sum(array)=missing number
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) { 4 long long sum1=0,sum2=0; 5 for (int num:nums) sum1+=num; 6 for (int i=0;i<nums.size()+1;i++) sum2+=i; 7 return sum2-sum1; 8 } 9 };
Solution 2: Use the bit manipulation XOR(exclusive or). XOR has the properties: A^A=0,A^0=A. XOR all the (2n+1) numbers, the result is the missing number.
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) { 4 int res=0,n=nums.size(); 5 for (int i=0;i<n;i++){ 6 res^=(i+1)^nums[i]; 7 } 8 return res; 9 } 10 };