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?
思路:
既然给出的数字是连续的,并且只有一个数字缺失,那么我们只需要求出前n项的和(n*(n+1)/2)再减去所给数字的和就是缺失的那个数字了。
Code:
int missingNumber(int* nums, int numsSize) { int sum1=0, sum2=(numsSize * (numsSize+1)) / 2; for(int i=0; i<numsSize; i++) { sum1 += nums[i]; } return sum2 - sum1; }