[TOC]
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/#/description
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
翻譯
- 理想時(shí)為打亂的[1,2,3...n],但是有的數(shù)字出現(xiàn)兩次,占據(jù)了位置,導(dǎo)致有的數(shù)字沒出現(xiàn)
- 返回沒出現(xiàn)的數(shù)字
思路
- 以num[0] = 4為例,其理想時(shí)出現(xiàn)位置應(yīng)該為num[3],即num[abs(num[0]) - 1],所以我們將num[3]位置的數(shù)先取絕對值在取反。
- 先取絕對值的原因是,因?yàn)樵撛乜赡芤呀?jīng)出現(xiàn),導(dǎo)致num[3]已經(jīng)變?yōu)樨?fù)數(shù)了,直接取反將變回初始狀態(tài)。
- 循環(huán)上述步驟,num中一些數(shù)字大于零,有些小于零,輸出大于零的數(shù)的下標(biāo)即可。
# Time O(2n) = O(n)
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for num in nums:
nums[abs(num) - 1] = -abs(nums[abs(num) - 1])
return [i + 1 for i, v in enumerate(nums) if v > 0]