描述
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1:
1 | Input: [3,0,1] |
Example 2:
1 | Input: [9,6,4,2,3,5,7,0,1] |
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
分析
0, 1, 2, ..., n
的和有个公式:
$\sum_{n}^{i=0}=\frac{n(n+1)}{2}$
所以可以先根据公式求和,再减去原数组的和就可以得到缺失的那个数字。时间复杂度是 O(n),空间复杂度是常数,符合题目的要求。
解决方案1(Java)
1 | class Solution { |
解决方案2(Python)
利用 Python 的列表-集合转换,集合相减运算可以用一行代码解决这个问题,唔,感觉有作弊嫌疑←_←
这个效率自然是不高的。
1 | class Solution: |
相关问题
(H) First Missing Positive
(M) Single Number
(H) Find the Duplicate Number