LeetCode 268 Missing Number
2017-08-04 17:04
357 查看
题目:
Given an array containing n distinct numbers taken from
find the one that is missing from the array.
For example,
Given nums =
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;
}
};
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;
}
};
相关文章推荐
- LeetCode 268: Missing Number
- Leetcode 268 Missing Number
- LeetCode[268] Missing Number
- Leetcode 268 Missing Number
- LeetCode 268 -Missing Number ( JAVA )
- LeetCode172 Factorial Trailing Zeroes. LeetCode258 Add Digits. LeetCode268 Missing Number
- LeetCode 268 Missing Number(丢失的数字)
- 【LEETCODE】268-Missing Number
- LeetCode - 268 - Missing Number
- leetcode 268: Missing Number
- LeetCode 268 Missing Number (位运算)
- 【LeetCode】268 Missing Number (java实现)
- leetcode【268 Missing Number】【Python】
- LeetCode 268 Missing Number
- leetcode268 Missing Number
- LeetCode(268) Missing Number
- leetcode 268 : Missing Number
- 【LeetCode】268 Missing Number (java实现)
- LeetCode 268 Missing Number
- leetcode268:Missing Number