题目名称
Missing Number—LeetCode链接
描述
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?
分析
考虑到将原数组排序后,如果不缺失元素,数组下标值和元素值是相等的,所以常规思路就是将数组排序,然后根据位置查找,如果丢失的是最后一个数字,则返回最后一个数字;否则从数组头部开始遍历,直到找到值与下标不相符的,返回下标数字。
C++代码
class Solution {
public:
int missingNumber(vector<int>& nums) {
sort(nums.begin(),nums.end());
int size = nums.size();
if(nums[size-1]==size-1)
return size;
for(int i=0;i<size;i++){
if(nums[i]!=i)
return i;
}
}
};
总结
这里给出一个非常棒的答案,不需要将原数组排序,而采用异或操作符^。先给出代码,再做解释:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int result = 0;
for (int i = 0; i < nums.size(); i++)
result ^= nums[i]^(i+1);
return result;
}
};
The operation of xor is commutative and associative. That is A ^ B = B^A and (A ^ B) ^ C = A ^ (B ^ C). Therefore, A^C^B^A^C = A^A^C^C^B = B. So for this code, the order of the numbers does not matter at all.
上段内容是这个代码的作者的解释,很好懂,举个例子,给定一个数组:
4,2,0,1
result初始值为0,做异或操作就是:0^(4^1)^(2^2)^(0^3)^(1^4)=3.
答案看上去很巧妙,其实思路很简单,给定的数组肯定缺失一个数字,那么我对数组所有元素(4,2,0,1)和不缺失的情况(0,1,2,3,4)中所有元素进行异或连接操作,肯定能得到缺失的那个数字。