iven 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:
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并不影响求和,所以可以用1-n元素的求和减去数组中所有元素的和,差值即为所缺失的元素,实现代码如下,时间复杂度为O(n),空间复杂度为O(1),满足题目要求。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int sum=0,sum2=0,n=nums.size();
sum=n*(n+1)/2;
for(int i=0;i<n;i++){
sum2+=nums[i];
}
return sum-sum2;
}
};