Description
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
分析
题目的意思是:找出一个数组缺少的值,这个数组只包含0~n,n+1为数组的大小。
- 等差数列求和,然后减去整个数组的和,相减就是剩下的了。
代码
class Solution {
public:
int missingNumber(vector<int>& nums) {
int sum=0;
int n=nums.size();
for(auto a:nums){
sum+=a;
}
return 0.5*n*(n+1)-sum;
}
};