268. Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

给出一个数组包含n个不同的从0到n取出的数,从中找出一个丢失的的数

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的所有数的和应该是sum=(1+n)*n/2,把数组中的数全部相加,然后用sum减去相加的和,就得出了缺少的数了。

 1 class Solution {
 2 public:
 3     int missingNumber(vector<int>& nums) {
 4         int sum=0,n=nums.size(),total=(n+1)*n/2;
 5         for(int num:nums){
 6             sum+=num;
 7         }
 8         return total-sum;
 9     }
10 };

 

posted @ 2016-07-17 16:04  ShawnChang  阅读(92)  评论(0编辑  收藏  举报