448. 找到所有數組中消失的數字
給定一個範圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另一些只出現一次。
找到所有在 [1, n] 範圍之間沒有出現在數組中的數字。
您能在不使用額外空間且時間複雜度爲O(n)的情況下完成這個任務嗎? 你可以假定返回的數組不算在額外空間內。
-
示例:
輸入:
[4,3,2,7,8,2,3,1]輸出:
[5,6]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
# 遍歷後將不存在的數字追加到最後,LeetCode 提示超時
class Solution:
def findDisappearedNumbers(self, nums):
length = len(nums)
if length < 1:
return None
for i in range(1,length+1):
if i not in nums[:length]:
nums.append(i)
return nums[length:]
# 置換法,將數組元素對應爲索引求反,爲負值。
class Solution:
def findDisappearedNumbers(self, nums):
if len(nums) < 1:
return None
length = len(nums)
for i in range(0,length):
nums[abs(nums[i])-1] = -abs(nums[abs(nums[i])-1])
return [i+1 for i, v in enumerate(nums) if v >= 0]
# 置換法,將數組元素對應爲索引,將該索引處的值加n
class Solution:
def findDisappearedNumbers(self, nums):
if len(nums) < 1:
return None
length = len(nums)
for i in range(0,length):
index = (nums[i]-1)%length
nums[index] += length
return [i+1 for i, v in enumerate(nums) if v <= length]
# 抽屜原理 + 基於“異或運算”交換兩個變量的值
from typing import List
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
# 基於異或運算交換數組兩個位置的元素,不使用額外的空間
def swap(nums, index1, index2):
# 這一步是必要的,否則會使得一個數變成 0
if index1 == index2:
return
nums[index1] = nums[index1] ^ nums[index2]
nums[index2] = nums[index1] ^ nums[index2]
nums[index1] = nums[index1] ^ nums[index2]
for i in range(len(nums)):
while nums[i] != nums[nums[i] - 1]:
# 如果不在位置上,並且它將要去的那個位置上的數不等於自己,則交換
swap(nums, i, nums[i] - 1)
return [i + 1 for i, num in enumerate(nums) if num != i + 1]
作者:liweiwei1419
鏈接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/solution/tong-pai-xu-ji-yu-yi-huo-yun-suan-jiao-huan-liang-/
題解:
-
枚舉遍歷,將元素插入到原數組之後,實際上佔用空間變大了。
-
置換方法:
- 將數組元素對應爲索引的位置加n,(注意:索引爲數組值 - 1),遍歷加n後的數組,若數組元素值小於等於n,則說明數組下標值不存在,即消失的數字;
- 取反,或是將將數組元素對應爲索引求反,數組值出現的節點值改爲負數,第二遍遍歷如果節點值爲正,則是沒有出現過的元素。
-
抽屜原理 + 基於“異或運算”交換兩個變量的值
下面直接給結論:“基於異或運算”利用了“異或運算”是不進位的二進制加法。它有如下性質:
如果 a ^ b = c ,那麼 a ^ c = b 與 b ^ c = a 同時成立,利用這一條,可以用於交換兩個變量的值。
於是,交換兩個變量的值,例如 a 和 b,不使用第三個變量,可以這樣做:
a = a ^ b
b = a ^ b
a = a ^ b這裏要特別注意一點,在數組中使用異或運算交換兩個變量的值的時候,一定要保證這兩個變量不是同一個變量,即索引不能相同,否則會把這個位置上的數變成 000 。