题目
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
Example 1
Input: [3,0,1]
Output: 2
Example 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
题意
这道题是说给出一个长度为N的数组,数组内容是从0-N的不同数字,找出那个缺失的(N+1 - N)的数字
想法
感觉这道题很有意思,乍一看,要求只有线性运算时间,又只用一个常量的辅助空间,貌似很难,但是仔细一想,有种会心的感觉,这不就是你目标序列已知了:(1)递增序列,从0开始到N,目标和已知;(2)互异,值唯一;
最后的解法就是先求目标和和实际和,相减得到那个唯一缺失值。
参考代码
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return (0+len(nums))*(1+len(nums))/2 - sum(nums)
寻找缺失数字
本文介绍了一种线性时间复杂度和常数额外空间复杂度的方法来找出长度为N的数组中缺失的一个数字,数组包含从0到N的不同整数。通过计算理想序列之和与实际序列之和的差值,快速定位缺失的数字。
347

被折叠的 条评论
为什么被折叠?



