题目如下:
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] 渣翻译如下: 给出一个从1-n的整形数组,其中有的数出现两次,有的只出现一次,找出从1-n中未出现的数。。。 在O(n)的时间内和不用额外空间,你能do it 吗?可以假定,返回的list不计入额外空间。
精彩代码如下:
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
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]
遍历list,将出现的值减1,即为出现的数的key,然后将其key所在值赋为负值。(加绝对值是为了防止重复出现的值变为正数)
然后再次遍历,value不为负值的,其key+1(key要再加一),即为未出现过的值。
取key赋为负值,真的6。。。。。我脑子可能真的有坑。。。
最后一行代码表示,返回遍历list,如果nums[i]值大于0,则返回其i+1(即key+1)。