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.
这题需要技巧,利用异或。
先将nums的数作异或得到x1;
将0-n+1都作异或得到x2;
missing number 就是x1^x2。
为什么呢?
假设缺少的值为A,则x2=x1^A,那么x1^x2=x1^(x1^A)=(x1^x1)^A=0^A=A,得证。
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) { 4 int result; 5 int x1=nums[0]; 6 for(int i=1;i<nums.size();i++) 7 { 8 x1^=nums[i]; 9 } 10 int x2=0; 11 for(int i=1;i<=nums.size();i++) 12 { 13 x2^=i; 14 } 15 result = x1^x2; 16 return result; 17 } 18 };