LeetCode--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?
代码:
int missingNumber(vector<int>& nums) { int x = 0; int y = 0; int z = 0; for(int i = 0; i < nums.size()+1; ++i) { x ^= i; } for(int i = 0; i < nums.size(); ++i) { y ^= nums[i]; } z = x^y; return z; }
运用异或,x为0~n异或,y为nums所有值异或,x^y即剩下miss的那个