LeetCode268: 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?
分析:
思路1:对数据进行排序,然后依次扫描,便能找出漏掉的数字,但是基于比较的排序算法的时间复杂度至少是nlog(n),不满足题目要求。
思路2:求和,对0到n求和,然后对给出的数组求和,二者之差即为漏掉的数字。但是这种方法不适用于0是漏掉的数字的情况,因为此时两个和是相同的。
思路3:按位异或操作
首先将0到n这些数进行异或运算,然后对输入的数组进行异或运算,最后将两个结果进行异或运算,结果便是漏掉的数字,因为其他数字在两个数组中都是成对出现的,异或运算会得到0。
[cc lang=”C++”]
int missingNumber(vector
int count = nums.size();
int result = 0;
for(int index =0; index < count; index ++)
{
result ^= index;
}
for(int index =0; index < count; index ++)
{
result ^= nums[index];
}
return result;
}
[/cc]
更简洁的写法是:
[cc lang="C++"]
class Solution {
public:
int missingNumber(vector
int result = nums.size();
int i=0;
for(int num:nums){
result ^= num;
result ^= i;
i++;
}
return result;
}
};[/cc]