给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入: [4,3,2,7,8,2,3,1] 输出: [5,6]
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result=[]
for i in range(1,len(nums)+1):
if i not in nums:
result.append(i)
return result
#超时间了
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for item in nums:
nums[abs(item)-1] = -abs(nums[abs(item)-1])
#如果索引出现,则把相应的位置设为负数,因为是本地修改,所以负数便于后续的操作
return [i + 1 for i, a_num in enumerate(nums) if a_num>0]
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return list(set(range(1,len(nums)+1))-set(nums))
执行用时: 240 ms, 在Find All Numbers Disappeared in an Array的Python3提交中击败了59.82% 的用户