您的位置:首页 > 其它

LeetCode 268 Missing Number

2017-08-04 17:04 357 查看
题目:

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个不同的元素,找到与0,1,2,3,4,,,,,n这个数组相比缺少的数,比如,数组[0, 1, 3],缺少2。

要求时间复杂度是线性的。

前几天做了一个类似的题目:LeetCode 645 Set Mismatch,一直在考虑利用下标做标记的方法,结果写的很麻烦,之后突然想到能不能用一个固定的数做差这种方法得出结果,然后写出了第二种思路,把所有数加起来,与正确的数组做差,差即为缺少的数。。。(这么简单一开始居然没想到,,,)。。。

代码如下:

class Solution {
public:
int missingNumber(vector<int>& nums) {
int sum = 0;
for (int i = 0; i < nums.size(); i ++)
sum += (i+1 - nums[i]);
return sum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: