#448. Find All Numbers Disappeared in an Array

[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]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容