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+1个数的递增数列nums应该是0,1,2,3.....,n。但现在这个数列只有n个数。请求出这n+1个数中缺失的那个。要求在线性时间内求解完毕。
思路:
因为从0开始,那么如果这个数列是完整的话。第n+1个数,也就是nums[n]==n==nums.size()-1。
理论上整个数列的和(nums[0]+nums[n])*(n+1)/2。也就是(0+n)*(n+1)/2;
为现在少了一个数,那么我们只要把整个nums中的数加起来,然后再用理论上的和减去nums中元素之和就是缺失的那个数了。
好了,上代码:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int total = ((0+n)*(n+1))/2;
for(int i = 0;i<nums.size();i++)
total -=nums[i];
return total;
}
};