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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
方法一:如果不缺失数的话,是从0到n的一个连续数组,注意到题目中只允许缺失一个数,因此,可以利用sum来解决,result = sum(all) - sum(missing array)。
public int missingNumber(int[] nums) {
int total = sum(nums.length);
int temp = 0;
for(int i = 0; i < nums.length; i++){
temp += nums[i];
}
return total - temp;
}
public int sum(int n){
return n * (n + 1) / 2;
}
方法二:类似single number的思想,除了missing number外,每一个数加上他的序列号都是出现两次的,只需要找出出现一次的数即可,利用XOR可解决,
public int missingNumber(int[] nums) {
int result = nums.length;
for(int i = 0; i < nums.length; i++){
result ^= i;
result ^= nums[i];
}
return result;
}