题目:给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。
思路:原地交换
复杂度:时间复杂度O(n) 空间复杂度O(1)
ps:时间复杂度为O(2n)也是O(n)的时间复杂度,不要总是觉得遍历两边复杂度就高了
'''
题目:给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。
思路:从前向后遍历 将当前值-1对应的index位置 置为负数 因为可能会出现两次,所以当其为正时候置为负数 出现第二次忽略即可。
复杂度:时间复杂度O(n) 空间复杂度O(1)
ps:时间复杂度为O(2n)也是O(n)的时间复杂度,不要总是觉得遍历两边复杂度就高了
例: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
4 3 2 7 8 2 3 1 -4 -3 -2 -7 8 2 -3 -1 返回 4+1 5+1
'''
def findDisappearedNumbers(nums):
for i in range(len(nums)):
if nums[abs(nums[i])-1] > 0:
nums[abs(nums[i])-1] *= -1
res = []
for i in range(len(nums)):
if nums[i] > 0:
res.append(i+1)
return res