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的和減去數組的和即爲缺失的數。
同樣也闊以異或操作,因爲只有缺失的數沒有成對。
int missingNumber(int* nums, int numsSize) {
if(nums == NULL || numsSize < 1)
return -1;
int miss = 0;
int max = 0;
for(int i = 0;i < numsSize;++i)
{
miss ^= nums[i];
if(nums[i] > max)
max = nums[i];
}
if(max + 1 == numsSize)
{
max = max + 1;
}
for(int i = 1;i <= max;++i)
miss ^= i;
return miss;
}