题目描述
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
思路1
类似剑指offer-数组中重复的数字 https://blog.csdn.net/m0_38098373/article/details/93989780
- 访问下标为【该数值-1】的元素和当前数一样时(说明此数为重复值),让当前数值为-1
- 如果当前值为-1时,则i+1,使循环继续
- 遍历数组,返回值为-1的【下标+1】,即为消失的数
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
i=0
while i<len(nums):
if nums[i]-1!=i:
if nums[nums[i]-1]!=nums[i]:
nums[nums[i]-1],nums[i]=nums[i],nums[nums[i]-1]
else:
nums[i]=-1
if nums[i]==-1:
i+=1
else:
i+=1
res=[]
for i in range(len(nums)):
if nums[i]==-1:
res.append(i+1)
return res
思路2
- 数值对应的数组下标的数,变为负数
- 如果有重复的数,变为负数的操作次数对应了重复的个数
- 遍历大于0的数,返回下标+1,即为消失的数
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
for num in nums:
nums[abs(num)-1]=-abs(nums[abs(num)-1])
res=[]
for i in range(len(nums)):
if nums[i]>0:
res.append(i+1)
return res