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

leetcode(448). Find All Numbers Disappeared in an Array

2017-08-10 19:21 627 查看

question

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array),

some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this

array.

Could you do it without extra space and in O(n) runtime? You may

assume the returned list does not count as extra space.

Example:

Input: [4,3,2,7,8,2,3,1]

Output: [5,6]

solution

leetcode(287). Find the Duplicate Number知道对于这样的问题通常都会转化为链表来解答,array[i].next = array[array[i]],因此这里我们可以遍历所有元素,分别以这些元素作为链表的头结点,把遍历到的元素置为-1,证明出现过等于这个index的元素,遍历结束后不是-1的元素的index就是未出现的元素。

class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
#超过了80%的提交

n = len(nums)
for num in nums:

while num != -1:
tmp = nums[num-1]
nums[num-1] = -1
num = tmp
return [i+1 for i in range(n) if nums[i]!= -1]


discussion

在leetcode上还看到了这样一种解法,使用原来的数对应的负数作为标记,这样的解法速度没有之前的快,但是标记的思路值得学习。

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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode