leetcode 448 find all numbers disappeared in an array

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:

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

Output:
[5,6]

  • 不允许用额外的空间,这样一来,只能用nums数组当做哈希表。
  • 遍历nums中的每一个数,如果nums[i]是一个正数,就把nums中第nums[i]-1位置的数字变为负数
  • 最终遍历一遍nums,所有为负的地方表示其index+1出现过
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class (object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
idx = abs(nums[i]) - 1
if nums[idx] < 0:
continue
else:
nums[idx] = -1 * nums[idx]
ans = []
for i in range(len(nums)):
if nums[i] > 0:
ans.append(i+1)
return ans