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,其中缺了一个数字,找到缺失的数字。
如果不考虑复杂度的话,可以先求0...n的数字的总和,然后减去给定数组的和,差值即为缺失的数字。
位操作中有特性 0^k = k
, k^k=0
所以可以把数组中所有数字都xor一遍,然后和0...n中所有数字xor,最后得到的结果就是缺失的数
public int missingNumber(int[] nums) {
int result = 0;
for (int i : nums) {
result^=i;
}
for (int i=0;i<=nums.length;i++) {
result^=i;
}
return result;
}