您的位置:首页 > 移动开发

LC-Find All Numbers Disappeared in an Array

2018-01-22 15:31 253 查看
方法1:

class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
hash = []
res = []
length = len(nums)
for i in range(length):
hash.append(0)
for i in range(length):
hash[nums[i]-1] +=1
for i in range(length):
if hash[i] == 0:
res.append(i+1)
return res

Sol = Solution()
print Sol.findDisappearedNumbers([4,3,2,7,8,2,3,1])


方法2:

class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# For each number i in nums,
# we mark the number that i points as negative.
# Then we filter the list, get all the indexes
# who points to a positive number
for i in xrange(len(nums)):
index = abs(nums[i]) - 1
nums[index] = - abs(nums[index])

return [i + 1 for i in range(len(nums)) if nums[i] > 0]


0,方法2的时间复杂度更小,是个更优秀的算法

1,方法2中,首先获得index,也就是表中存在的元素所对应的位置,类hash的方式。

2,方法2将表中所有的存在元素对应的位置的值全部置为负值,这样最后返回表中不为负值的位置即可, 因为该位置的数值不为负说明对应位置的数字不存在与表中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: