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]
思路:刚开始想到这个题的时候,很自然的准备使用字典,先保存所有的key键即数组中每个数的值,然后遍历数组出现次数作为value值,最后遍历字典,找出value值为0的key值将其存入结果列表中返回。问题是这个思路实在是太麻烦了,需要用到三个for循环,而且题目中要求不能使用额外的空间,字典dict和列表result都是额外空间。
代码:
class Solution:
def findDisappearedNumbers(self, nums):
dic = {}
result=[]
l = len(nums)
for i in range(1,l+1):
dic[i]=0
for num in nums:
dic[num]=dic.get(num,0)+1
for key,value in dic.items():
if value==0:
result.append(key)
return result
大神思路:这道题其实还是没有申清楚题目,已经说了所有的数都在1到n之间,那么这些数就可以对应nums数组中相应的下标。如[4,3,2,7,8,2,3,1]中对应下标[3,2,1,6,7,1,2,1]。我们发现只有下标4,5没有被对应,那么根据这个特性,我们把能对应到的数组的值都变为相反数,则当重新循环nums数组时,数值为正的数的下标就是我们要找的数.
大神代码:
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]