Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
原题地址: Missing Number
难度: Easy
题意: 存在一个长度为n的数组,其中数值包括在[0, n]之中,返回缺少的那个数
思路1:
(1)类似217. Contains Duplicate@python,采用正负计数方式,将数组中的值与数组索引对应.
(2)遍历数组,将值对应的索引变为负数
注意: 存在0这个数值,如果0对应的索引就是缺少的值,那么很可能找不到要求的值,所以给数组添加一个值,同时也防止 out of range .
代码:
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) nums.append(n+1) for i in range(n): idx = abs(nums[i]) nums[idx] = -nums[idx] tmp = None for i in range(n+1): if nums[i] > 0: return i elif nums[i] == 0: tmp = i return tmp
时间复杂度: O(n)
空间复杂度: O(1)
思路2:
思路1这种方式不够简洁,处理0这个干扰项.因为数组长度为n,数组内的值在0-n之间,并且缺少一个值.因此,相当于0这个值代替的缺少的值,采用和相减的方式可以求出缺少的值
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) total = (1 + n) * n / 2 return total - sum(nums)
时间复杂度: O(n)
空间复杂度: O(1)