題目描述
給定一個範圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另一些只出現一次。
找到所有在 [1, n] 範圍之間沒有出現在數組中的數字。
您能在不使用額外空間且時間複雜度爲O(n)的情況下完成這個任務嗎? 你可以假定返回的數組不算在額外空間內。
示例:
輸入:
[4,3,2,7,8,2,3,1]
輸出:
[5,6]
解法一:
-
將所有正數作爲數組下標,置對應數組值爲負值。那麼,仍爲正數的位置即爲(未出現過)消失的數字。
-
舉個例子:
原始數組:[4,3,2,7,8,2,3,1] 重置後爲:[-4,-3,-2,-7,8,2,-3,-1]
-
結論:[8,2] 分別對應的index爲[5,6](消失的數字)
# 時間複雜度O(2n),空間複雜度 $O(1)$,res 不算額外空間
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for num in nums:
index = abs(num) - 1
# 始終保持nums[index]爲負數
nums[index] = -abs(nums[index])
return [i + 1 for i, num in enumerate(nums) if num > 0]
解法二:
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
s = set(nums)
return [i+1 for i in range(len(nums)) if (i+1) not in s]
解法三:
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return list(set(range(1, len(nums)+1)) - set(nums))
解法四:
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
newnums = set(nums)
for i in range(1, len(nums) + 1):
if i not in newnums:
res.append(i)
print(newnums, len(nums))
return res