算法15-----找到所有數組中消失的數字
阿新 • • 發佈:2018-05-10
時間 spa 任務 索引 nbsp abs end pan red
1、題目:
給定一個範圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另一些只出現一次。
找到所有在 [1, n] 範圍之間沒有出現在數組中的數字。
您能在不使用額外空間且時間復雜度為O(n)的情況下完成這個任務嗎? 你可以假定返回的數組不算在額外空間內。
示例:
輸入: [4,3,2,7,8,2,3,1] 輸出: [5,6]
2、代碼:將該值對應到索引下,索引值變為負數,最後為整數的索引為所求。
def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int]""" """ [-4, -3, -2, -7, 8, 2, -3, -1] ^ """ for x in nums: if nums[abs(x)-1] > 0: nums[abs(x)-1] *= -1 ans = [] for i in range(len(nums)): if nums[i] > 0: ans.append(i+1) return ans
算法15-----找到所有數組中消失的數字