原题链接 https://leetcode.com/problems/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?
也就是说 连续的0~n 包含n在内,给出n个数 找出没出现的一个
我的方法是使用位运算进行异或操作
首先
ans = 0^1^2...^n;
然后在将给出数组中出现的数全部异或起来在与ans异或就得出没有的那个数
0^1
给出0 得到1,给出1得到0
class Solution {
public:
int missingNumber(vector<int>& nums) {
int ans = 0;
for(int i = 1; i <= nums.size(); ++i)
ans ^= i;
for(int i = 0; i < nums.size(); ++i)
ans ^= nums[i];
return ans;
}
};